gpt4 book ai didi

javascript - 为什么已经生成的使用 'new'操作的对象可以访问稍后在javascript中添加的原型(prototype)方法

转载 作者:行者123 更新时间:2023-11-28 15:38:38 26 4
gpt4 key购买 nike

代码如下:

function Building(b_height,b_address,b_cost){   
this.b_address = b_address;
this.b_cost = b_cost;
}

Building.prototype = {
constructor:Building,
}

var house = new Building("No.211 Spring Street",5000);

//add a new method to Building.prototype
Building.prototype.raise= function(){this.b_cost = this.b_cost + 1000;}

//why a object that already generated use 'new' operate can access a prototype's method which added later
house.raise();

house.b_cost ; //6000

我不明白为什么“house”对象可以访问方法的“raise”。

根据MDN对于NEW运算符的介绍:

When the code new foo(...) is executed, the following things happen:

(1)A new object is created, inheriting from foo.prototype.

(2)The constructor function foo is called with the specified arguments and this bound to the newly created object. new foo is equivalent to new foo(), i.e. if no argument list is specified, foo is called without arguments.

(3)The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

那么,‘house’作为一个新对象只能继承自Building.prototype,为什么可以访问prototype的“new”方法呢?

最佳答案

当对象继承原型(prototype)时,它不会获得原型(prototype)的副本,而是获得对原型(prototype)的引用。

创建对象实例后,您仍然可以更改其原型(prototype),因为同一类型的所有对象都只有一个原型(prototype)对象。

关于javascript - 为什么已经生成的使用 'new'操作的对象可以访问稍后在javascript中添加的原型(prototype)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24694383/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com