如何正确构建JS子伪类的原型?

时间:2016-05-05 10:32:54

标签: javascript prototype pseudo-class

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

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的{​​{1}}并在那里找到该功能吗?任何人都可以解释和解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

您遇到的问题是msgbox的参数应为Object.create

这是工作代码

Car.prototype

Mozilla docs始终是这类问题的绝佳参考