【发布时间】:2016-05-05 20:09:01
【问题描述】:
制作子类很容易。我只是遵循这个结构:
var Car = function(x){
this.x = x;
this.y = 10;
};
Car.prototype.say_position = function(){
console.log("("+this.x+", "+this.y+")");
}
var a = new Car(2);
a.say_position(); //(2, 10)
对类使用原型对性能有好处,因为每个实例都不会重复该方法。为了制作子类,我遵循了这里解释的约定:https://www.udacity.com/course/object-oriented-javascript--ud015 如下:
var Car = function(x){
this.x = x;
this.y = 10;
};
var Van = function(x){
Car.apply(this, arguments);
};
Van.prototype = Object.create(Car);
Van.prototype.constructor = Car;
同时,当我尝试使用具有这种结构的原型方法时......
var Car = function(x){
this.x = x;
this.y = 10;
};
var Van = function(x){
Car.apply(this, arguments);
};
Van.prototype = Object.create(Car);
Van.prototype.constructor = Car;
Car.prototype.say_position = function(){
console.log("("+this.x+", "+this.y+")");
}
var car = new Car(2);
car.say_position(); //(2, 10)
var van = new Van(2);
van.say_position(); //Error!
如您所见,在 van 上调用 say_position() 时,会引发错误。 Van 的prototype 不应该委托给Car 的prototype 并在那里找到该功能吗?谁能解释和解决这个问题?
【问题讨论】:
-
不,您将委派给
Car,而不是Car.prototype。
标签: javascript prototype pseudo-class