如何在Javascript中从子类对象访问父类属性

时间:2017-03-26 19:27:14

标签: javascript this bind

有一个名为Vehicle

的类
    function Vehicle() {
    this.amount = 1000;
    }

并且有一个名为car的类从车辆延伸

    function Car() {}

    Car.prototype = Object.create(Vehicle.prototype);
    Car.prototype.constructor = Car;
    var car = new Car();
    console.log(car.amount);

我想使用car object打印金额。这意味着输出应为1000。 这就是我尝试这样做的方式。但是这不起作用。在这种情况下  我该如何使用bind

function Vehicle() {
  this.amount = 1000;
}

function Car() {}

Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car;
var car = new Car();

console.log(car.amount);

1 个答案:

答案 0 :(得分:1)

您错过了属性与car函数内对象的绑定:
您需要在car函数中执行Vehicle并使用vehicle将其传递给call函数。现在,Vehicle函数的所有属性都绑定到car对象。

Vehicle.call(this);添加到您的car功能中,它会起作用。

更多内容请阅读Object.create



function Vehicle() {
  this.amount = 1000;
}

function Car() {
   Vehicle.call(this); //calling the Vehicle function and bind the properties to this (or where the inheritance is really effectuated)
}

Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car;
var car = new Car();

console.log(car.amount);