I simply try to override the fields and functions from Car class. How to override existent fields and functions?
Car = function()
{
this.doors = null;
this.open = function(){alert("open it!");}
}
Car.prototype.doors = 4;
Car.prototype.open = function(){ // public method
alert("do not open!");
}
myCar = new Car();
alert(myCar.doors); //null?
See, prototype
is not some magic trick allowing you to extend an object. Its only purpose is to serve values for properties not found in the corresponding object. Here, both doors
and open
are defined for a Car
object, that's why any look-up won't even reach Car.prototype
.
And that's easy to prove: just add these lines to your code
delete myCar.doors;
alert(myCar.doors); // 4
Explanation: with delete myCar.doors
the corresponding property is removed from an object. When you look-up for its value in the next line, it goes up the prototype chain, reaching Car.prototype.doors
- which value is set to 4.
That's why, btw, prototype chain
is rarely used for setting static values for a specific class. But it's very useful for setting up so-called class methods, as only a single copy of a function will be created and stored in memory.
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.