Here I made two objects; one has accessor methods created in the constructor, the other in the prototype. Why would one choose one of these over the other?
function spy1(name){
this.name = name;
var secret;
this.setSecret = function(message){
secret = message;
};
this.getSecret = function(){
return secret;
};
}
function spy2(name){
this.name = name;
this.secret;
/* (see comment) was:
var secret;
*/
}
spy2.prototype.setSecret = function(message){
this.secret = message;
/*was:
secret = message;
*/
};
spy2.prototype.getSecret = function(){
return this.secret;
/*was:
return secret;
*/
};
bond = new spy1("007");
smart = new spy2("86");
bond.setSecret("CONTROL is a joke.");
smart.setSecret("The British Secret Service is for sissies.");
The primordial differrence is that in your first example, without prototype, the
getSecretandsetSecretfunction implementation will reside on every instance of spy1.On your second example, the functions are defined on the prototype, and all instances refer to them directly, you can test it:
Also note what @T.J. commented, in your second example, using the prototype, you don’t have access to the constructor function closure, and for that you are making a
window.secretglobal variable.If you intend to work with privileged methods, extending the prototype is not an option, all the methods that need access to the variables defined within the scope of the constructor function need to be declared inside of it…
See also: Closures.