2017-10-04 12 views
0

以下代碼的輸出是undefined has undefined wheels而不是Bike has 2 wheelsInstantiated object不可能調用未附加到任何對象的prototype的函數嗎?如何使用'Function.prototype.call'來調用未附加到任何對象原型的函數

var vehicle = function(name, wheels){ 
 
\t name = "car", 
 
\t wheels = 4, 
 
\t fuel = "petrol" 
 
} 
 

 
function drive(name, wheels) { 
 
\t console.log(this.name + " has " + this.wheels + " wheels"); 
 
} 
 

 
var vehicle1 = new vehicle('Bike' , 2); 
 
drive.call(vehicle1); //undefined is driven with undefined wheels

+2

裏面的'vehicle'功能則需要使用定義這些變量'本'....,例如:'this.name =「汽車」。 – Titus

+1

你的車輛構造函數應該這樣做。name = ...'將變量附加到實例。你只是聲明瞭隱式全局變量。 – Li357

+0

還有,'車有4個車輪' – Prem

回答

4

不幸的是,幾乎所有關於你的代碼不正確。

首先,「車輛」的功能必須在this設置屬性,它應該使用傳入的參數,而不是常量:

var vehicle = function(name, wheels) { 
    this.name = name, 
    this.wheels = wheels, 
    this.fuel = "petrol" 
} 

然後,你的功能「驅動器」應該沒有任何參數:

function drive() { 
    console.log(this.name + " is driven with " + this.wheels + " wheels"); 
} 

要撥打drive()與您的汽車作爲this值:

var vehicle1 = new vehicle("Bike", 2); 
drive.call(vehicle1); 

.call()的第一個參數將用作被調用函數內部的this的值。

0

您需要使用this這樣的:

var vehicle = function(name, wheels){ 
 
\t this.name = "car", 
 
\t this.wheels = 4, 
 
\t this.fuel = "petrol" 
 
} 
 

 
function drive(name, wheels) { 
 
\t console.log(this.name + " is driven with " + this.wheels + " wheels"); 
 
} 
 

 
var vehicle1 = new vehicle('Bike' , 2); 
 
drive.call(vehicle1); //undefined is driven with undefined wheels

3

幾個問題:

  1. 您使用vehicle作爲一個構造函數,而不是this指定的任何屬性。

  2. 你不使用namewheels參數vehicle

  3. 你定義namewheels參數drive但不使用他們,而不是調用它時向他們提供。

  4. 不是一個真正的問題,只是約定(如我上your last question提到的):如果你打算使用newvehicle,應該首先上限:Vehicle通過壓倒性約定。

看評論:

var vehicle = function(name, wheels){ 
 
    // Actually use name and wheels and put them on `this` 
 
    this.name = name; 
 
    this.wheels = wheels; 
 
}; // <== Added missing ; 
 

 
function drive(/* No parameters here*/) { 
 
\t console.log(this.name + " is driven with " + this.wheels + " wheels"); 
 
} 
 

 
var vehicle1 = new vehicle('Bike' , 2); 
 
drive.call(vehicle1);

相關問題