我是Codeyear老乡,不幸原型对象的概念没有解释。我google了一下,发现tutorial。在学习之后,我的理解是,我们使用原型对象继承来节省内存并在对象之间共享公共属性。 对不对?如果是的话,你不觉得下面的代码是坏习惯。由于汽车制造商已经定义了价格,速度和getPrice,为什么我们需要再次定义相同的事物,因为我们正在使用继承的概念。请解释 。下面是代码。原型对象继承
function Car(listedPrice) {
var price = listedPrice;
this.speed = 0;
this.getPrice = function() {
return price;
};
}
Car.prototype.accelerate = function() {
this.speed += 10;
};
function ElectricCar(listedPrice) {
var price = listedPrice;
this.speed = 0;
this.getPrice = function() {
return price;
};
}
ElectricCar.prototype = new Car(); // Please also explain why car constructor
// is not thowing error since we are not passing
// listedPrice parameter
myElectricCar = new ElectricCar(500);
console.log(myElectricCar instanceof Car);
这可能会帮助你:http://stackoverflow.com/questions/10836064/what-does-anobject-prototype-constructor-do – Sarfraz