如何正确原型化 JS 子伪类?

How to properly prototype JS sub-pseudoclasses?

制作子类很容易。我只是遵循这个结构:

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)

使用 类 的原型有利于提高性能,因为每个实例都不会重复该方法。为了制作 sub类 我遵循了这里解释的约定: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() 时,它会抛出错误。 Vanprototype 不应该委托给 Carprototype 并在那里找到那个函数吗?谁能解释并解决这个问题?

您遇到的问题是 Object.create 的参数应该是 Car.prototype

这是工作代码

var Car = function(x){
    this.x = x;
    this.y = 10;
}; 

var Van = function(x){
    Car.apply(this, arguments);
};
Van.prototype = Object.create(Car.prototype); 
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(); //(2, 10)

Mozilla docs 始终是此类问题的重要参考