如果您在原型上设置它,则该属性由所有实例共享。通常不是你想要的。我在http://js-bits.blogspot.com/2014/10/understanding-prototypical-inheritance.html上写了一篇博客。您通常希望每个小工具都有自己的名称和颜色。您将如何使用您建议的代码来做到这一点?
顺便说一句,您建议的代码有未定义的变量(名称,颜色)
通常的方法是在原型上设置方法,在对象本身上设置常规值。除非您确实希望所有实例共享一个属性,否则就像我们在静态类型语言中所说的静态属性一样。
这是一个例子
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;
};
要记住的一个重要概念是写入(分配)总是应用于对象本身,而不是原型。然而,读取将遍历原型链以查找该属性。
那是
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