所以我听说过应该在构造函数的原型(prototype)属性中设置方法,这样它就不会有多个不同的实例。但是属性本身呢?哪个是最佳实践?如果是这样,构造函数不应该总是空的吗?
function Gadget(name, color) {
this.name = name;
this.color = color;
this.whatAreYou = function(){
return 'I am a ' + this.color + ' ' + this.name;
}
}
这实际上应该是...?
function Gadget(name,color){}
Gadget.prototype.name = name;
Gadget.prototype.color = color;
Gadget.prototype.whatAreYou = function() {
return 'I am a ' + this.color + ' ' + this.name;
};
最佳答案
如果在原型(prototype)上设置它,该属性将被所有实例共享。通常不是你想要的。我在 http://js-bits.blogspot.com/2014/10/understanding-prototypical-inheritance.html 上写了这篇博客.您通常希望每个小工具都有自己的名称和颜色。您将如何使用您建议的代码来做到这一点?
顺便说一句,你建议的代码有 undefined variable (名称、颜色)
通常的方法是在原型(prototype)上设置方法,在对象本身上设置常规值。除非您确实希望所有实例共享一个属性,否则这就像我们在静态类型语言中所说的静态属性。
举个例子
function Gadget(name,color){
this.name = name;
this.color = color;
// Since all gadgets in on the prototype, this is shared by all instances;
// It would more typically be attached to Gadget.allGadgets instead of the prototype
this.allGadgets.push(this);
// Note that the following would create a new array on the object itself
// not the prototype
// this.allGadgets = [];
}
Gadget.prototype.allGadgets = [];
Gadget.prototype.whatAreYou = function() {
return 'I am a ' + this.color + ' ' + this.name;
};
要记住的一个重要概念是写入(赋值)总是应用于对象本身,而不是原型(prototype)。然而,读取将遍历原型(prototype)链寻找该属性。
也就是
function Obj() {
this.map = {};
}
function SharedObj() {}
SharedObj.prototype.map = {};
var obj1 = new Obj();
var obj2 = new Obj();
var shared1 = new SharedObj();
var shared2 = new SharedObj();
obj1.map.newProp = 5;
obj2.map.newProp = 10;
console.log(obj1.map.newProp, obj2.map.newProp); // 5, 10
// Here you're modifying the same map
shared1.map.newProp = 5;
shared2.map.newProp = 10;
console.log(shared1.map.newProp, shared2.map.newProp); // 10, 10
// Here you're creating a new map and because you've written to the object directly
// You don't have access to the shared map on the prototype anymore
shared1.map = {};
shared2.map = {};
shared1.map.newProp = 5;
shared1.map.newProp = 10;
console.log(shared1.map.newProp, shared2.map.newProp); // 5, 10
关于Javascript - 在构造函数或构造函数的原型(prototype)属性中设置属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15748521/