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

why the values of properties in the prototype are inconsistent?

本文关键字:不一致 属性 原型 为什么      更新时间:2023-09-26

我调用了console.log(Family.prototype.money),值是200,这证实了asset是函数Family的原型。但是当我调用console.log(other.money)时,值是 1000,我之前将其分配给原型。这是怎么回事?看起来对象 other 的原型与函数 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