如何正确地原型JS子伪类

How to properly prototype JS sub-pseudoclasses?

本文关键字:JS 原型 正确地      更新时间:2023-09-26

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

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()时,它会抛出一个错误。难道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文档对于这些类型的问题始终是一个很好的参考