为什么原型中的属性值不一致?

时间:2015-01-21 01:55:55

标签: javascript prototype

我致电console.log(Family.prototype.money),价值为200,这证实asset是函数Family的原型。但是当我调用console.log(other.money)时,值为1000,我之前分配给原型。这有什么不对?它看起来像对象的原型不同于函数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;

1 个答案:

答案 0 :(得分:0)

函数的prototype不是实例对象的实际原型。使用new时,prototype对象将用作内部[[Prototype]]属性的模板,在某些浏览器中显示为__proto__。因此,在更改prototype之前,此表达式为true

Family.prototype === other.__proto__ // true
Family.prototype = asset;

在你改变之后,它是false

Family.prototype = asset;
Family.prototype === other.__proto__ // false