为什么原型中的属性值不一致?
why the values of properties in the prototype are inconsistent?
我调用了console.log(Family.prototype.money)
,值为200,证实asset
是函数Family
的原型。但是当我调用 console.log(other.money)
时,值是 1000,这是我之前分配给原型的。这里有什么问题?看起来object other的原型和function Family的原型不一样,这和我在面向对象Javascript这本书上看到的完全矛盾。
function Family(father, mother, children){
this.father = father,
this.mother = mother,
this.children = children,
this.num = function(){
return (this.children.length+2);
}
}
Family.prototype.money = 1000; // notice!!!!
var myFamily = new Family('Hung', 'Hong', ['Phuong', 'Lien', 'Hiep']);
var other = new myFamily.constructor('Lan', 'Linh', ['Tung']);
var money = other.money;
var asset = {
money: 200,
car: 2,
house: 10
}
Family.prototype = asset;
函数的prototype
并不是实例对象的实际原型。当您使用 new
时,prototype
对象用作内部 [[Prototype]]
属性 的模板,在某些浏览器中显示为 __proto__
。因此,在更改 prototype
之前,此表达式为 true
:
Family.prototype === other.__proto__ // true
Family.prototype = asset;
改完之后就是false
:
Family.prototype = asset;
Family.prototype === other.__proto__ // false
我调用了console.log(Family.prototype.money)
,值为200,证实asset
是函数Family
的原型。但是当我调用 console.log(other.money)
时,值是 1000,这是我之前分配给原型的。这里有什么问题?看起来object other的原型和function Family的原型不一样,这和我在面向对象Javascript这本书上看到的完全矛盾。
function Family(father, mother, children){
this.father = father,
this.mother = mother,
this.children = children,
this.num = function(){
return (this.children.length+2);
}
}
Family.prototype.money = 1000; // notice!!!!
var myFamily = new Family('Hung', 'Hong', ['Phuong', 'Lien', 'Hiep']);
var other = new myFamily.constructor('Lan', 'Linh', ['Tung']);
var money = other.money;
var asset = {
money: 200,
car: 2,
house: 10
}
Family.prototype = asset;
函数的prototype
并不是实例对象的实际原型。当您使用 new
时,prototype
对象用作内部 [[Prototype]]
属性 的模板,在某些浏览器中显示为 __proto__
。因此,在更改 prototype
之前,此表达式为 true
:
Family.prototype === other.__proto__ // true
Family.prototype = asset;
改完之后就是false
:
Family.prototype = asset;
Family.prototype === other.__proto__ // false