Using the prototype makes for faster object creation, since that function does not have to be re-created each time a new object is created.(使用原型可以更快地创建对象,因为不必在每次创建新对象时都重新创建该功能。)
When you do this:(执行此操作时:)
function animal(){
this.name = 'rover';
this.set_name = function(name){
this.name = name;
}
}
The set_name
function is created de novo each and every time you create an animal.(每次创建动物时,都会从头创建set_name
函数。) But when you do this(但是当你这样做)
animal.prototype.set_name = function(name){
this.name = name;
}
The function does not have to be re-created each time;(不必每次都重新创建该函数;) it exists in one place in the prototype.(它存在于原型中的一个地方。) So when you call someAnimal.set_name("Ubu");
(因此,当您调用someAnimal.set_name("Ubu");
) the this
context will be set to someAnimal
and (the one and only) set_name
function will be called.(this
上下文将被设置为someAnimal
,并且将调用(唯一的) set_name
函数。)
There is one advantage to using the first syntax though: functions created in this manner will have access to private data:(但是,使用第一种语法有一个优点:以这种方式创建的函数将可以访问私有数据:)
function animal(){
var privateData = 'foo'
this.name = 'rover';
this.set_name = function(name){
this.name = name;
alert(privateData); //will alert 'foo'
}
}
Douglas Crockford calls functions created like this "privileged" for that reason: they have access to both public, and private data.(出于这个原因,Douglas Crockford将这样创建的函数称为“特权”:它们可以访问公共数据和私有数据。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…