我是Codeyear研究员,不幸的是没有解释原型对象的概念。我在谷歌上搜索并找到了教程。经过学习,我的理解是我们使用原型对象继承来节省内存并在对象之间共享公共属性。我对吗 ?如果是,你不认为下面的代码是不好的做法。由于汽车构造函数已经定义了价格、速度和 & 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);