Possible Duplicate:
Use of 'prototype' vs. 'this' in Javascript?
My understanding of the different kinds of JavaScript functions are as follows:
function MyObj() { this.propOne = true; this.publicInstanceFunc = function() { if (propOne) return 'public instance function'; } function privateFunc() { return 'private function only visible inside this constructor'; } } MyObj.prototype.protoFunc = function() { if (this.propOne) return 'prototype function shared amongst all instances of MyObj'; }
protoFunc
) vs. in the constructor (e.g. publicInstanceFunc
)?this
the correct way to access properties inside prototype functions?While a function definition specifies how the function does what it does (the "implementation"), a function prototype merely specifies its interface, i.e. what data types go in and come out of it.
Prototypes allow you to easily define methods to all instances of a particular object. The beauty is that the method is applied to the prototype, so it is only stored in the memory once, but every instance of the object has access to it.
There is a clear reason why you should use prototypes when creating classes in JavaScript. They use less memory. When a method is defined using this. methodName a new copy is created every time a new object is instantiated.
'Prototype' helps remove code redundancy which helps boost your app's performance. If you are seeking to optimize resources or memory on your application, you should use prototype .
You can actually add another level of privilege via wrapping the whole thing in a self-executing function:
var MyObj = (function() { // scoping var privateSharedVar = 'foo'; function privateSharedFunction() { // has access to privateSharedVar // may also access publicSharedVar via explicit MyObj.prototype // can't be called via this } function MyObj() { // constructor var privateInstanceVar = 'bar'; this.publicInstanceVar = 'baz'; function privateInstanceFunction() { // has access to all vars // can't be called via this }; this.publicInstanceMethod = function() { // has access to all vars // also known as a privileged method }; } MyObj.prototype.publicSharedVar = 'quux'; MyObj.prototype.publicSharedMethod = function() { // has access to shared and public vars // canonical way for method creation: // try to use this as much as possible }; return MyObj; })();
Only 'public' properties can be accessed from outside via this
.
For performance reasons, you should avoid what I called 'instance' methods: For each of these, a new function object must be created for each MyObject
instance, whereas there's only a single function object per 'shared' method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With