The following code binds the say
function to the object prototype. When you create a Person
instance, the function is called against the data in this
instance.
Person.prototype.say = function (words) {
alert(this.name + ' says "' + words + '"');
};
The following code binds the say
function to the object in a static fashion (thus, not available per-instance)
Person.say = function (words) {
alert(this.name + ' says "' + words + '"');
};
The following alternative is this, which is a per-instance function, but is not bound to the prototype, rather the say function is created per instance, in the same way that name
is created.
Just FYI, this method is NOT recommended (I'm just adding this for completeness) - It is recommended to bind your instance functions to the prototype:
var Person = function(name) {
this.name = name;
this.say = function(words) {
alert(this.name + " says " + words);
};
};
Prototype vs Per-instance:
Binding functions to the prototype (Person.prototype.say = function...
) consumes less memory as one function is shared across all instances of the object.
Binding functions per-instance (this.say = function...
) consumes more memory because a function is created for every instance created (nothing is shared), though this has the advantage of being able to access private members, which is not possible with prototype bound functions.
Overview:
Static binding: Person.say = function() { ... }
Prototype binding: Person.prototype.say - function() { ... }
Instance binding: function Person() { this.say = function() { ... } ... }