2017-03-26 29 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