简体   繁体   English

卡在 javascript 中的 object inheritance

[英]stuck with object inheritance in javascript

I'm trying to understand the object inheritance in js by building a base constructor and working through that but its not working for me.我试图通过构建一个基本构造函数并通过它来理解 js 中的 object inheritance 但它对我不起作用。 I have gone wrong somewhere in my code:我的代码某处出错了:

function car(make, model, transmission) {
    this.make = make;
    this.model = model;
    this.transmission = transmission;
    this.report = function() {
        return ("make " + this.make + "model " + model);
    }

}

function SUV(make, model, transmission, mpg) {
    this.mpg = mpg;
    this.carInfo = car;
    this.carInfo = (make, model, transmission);

}
SUV.prototype = new Car();
SUV.prototype.getMPG = function() {
    return "the suv mpg is" + this.mpg;
}
mySuv = new Suv("nissan", "almera", "manual", 12);
document.writeIn(newSuv + report());

You do not inherit just by assigning the parent class to an instance method (which you immediately overwrite anyway).您不仅仅通过将父 class 分配给实例方法(无论如何您都会立即覆盖)来继承。

Instead, you must call the parent constructor on this :相反,您必须在this上调用父构造函数:

function SUV(...) {
    car.call(this, ...);
    ....
}

call allows you to specify what this will refer to in the parent method. call允许您指定this将在父方法中引用的内容。 car.call(this, ...) is equivalent to: car.call(this, ...)相当于:

this.car_funk = car
this.car_funk(...);
delete this.car_funk;`

Or this:或这个:

car.bind(this)(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM