简体   繁体   中英

why a object that already generated use 'new' operate can access a prototype's method which added later in javascript

code as follow:

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

I don't understand why 'house' object can access 'raise' of method.

according to MDN for the introduction of NEW operator:

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(), ie 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.)

then, 'house' as A new object only inherit from Building.prototype ,why can access a "new" method of prototype?

When the object inherits the prototype it doesn't get a copy of the prototype, it gets a reference to the prototype.

After object instances are created, you can still change their prototype, because there is only one prototype object for all objects of the same type.

JS is a dynamic language, if you have access to the prototype you can augment it with new methods that will be available from that point on to whoever has access to the prototype.

In JS the inheritance is object based not class based as in C# for example. So it is more like composition than inheritance. Since you have access to the prototype you get the instance of the prototype and whatever methods and fields it has at that time.

I hope I expressed myself well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM