2017-03-26 32 views
1

父类属性有一个叫车如何从子类对象访问的Javascript

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); 

我想延长一类叫车使用汽车object.it意味着输出应该是1000. 这是我如何试图做到这一点,但它不工作。在这种情况下 如何使用绑定

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

你错过属性的结合car函数内部对象:
您需要执行Vehicle汽车函数内部,并通过它的参考使用callvehicle功能。现在,车辆功能的所有属性都绑定到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);

+0

什么是通话和bind.how之间的区别我可以在这种情况下使用绑定 –

+0

[绑定](https://developer.mozilla.org/nl/docs/Web/ JavaScript/Reference/Global_Objects/Function/bind)创建一个包含原始文件的新函数。在执行时,它将按照指定的方式传递这个关键字。调用允许您传递一个不同的引用,然后传递该函数的所有者,然后执行该函数。 – Mouser