2016-03-11 46 views
-3

傳遞參數給我們的構造使唯一對象:傳遞參數給我們的構造使唯一對象

我們構造函數是偉大的,但如果我們不總是要創建同一個對象是什麼?

要解決這個問題,我們可以將參數添加到我們的構造函數中。我們這樣做是類似於下面的示例:

var Car = function(wheels, seats, engines) { 
    this.wheels = wheels; 
    this.seats = seats; 
    this.engines = engines; 
}; 

現在我們可以在參數傳遞的時候,我們調用構造函數。

var myCar = new Car(6, 3, 1); 

此代碼將創建一個使用我們傳遞的參數,看起來像一個對象:

{ 
    wheels: 6, 
    seats: 3, 
    engines: 1 
} 

現在給它一個嘗試一下吧!修改Car constructor以使用parameters將值分配給wheels, seats, and engines屬性。

然後用三個數字參數呼叫您的新constructor,並將其分配給myCar以查看它的行動。


請填寫下面給出的代碼:

var Car = function() { 
    //Change this constructor 
    this.wheels = 4; 
    this.seats = 1; 
    this.engines = 1; 
}; 

//Try it out here 
var myCar; 

說明:

  • 調用new Car(3,1,2)應該產生一個對象與012的 屬性,1的seats屬性,和2.

  • 調用new Car(4,4,2)應該產生一個對象爲4的wheels
    屬性,4的seats屬性的屬性enginesengines屬性的2.

  • 調用new Car(2,6,3)應該產生一個對象爲2的wheels
    屬性,爲6的seats屬性,和爲3 engines屬性。

  • myCar應具有wheels, seats, and engines
    屬性的數值。


我嘗試:

var Car = function() { 
    //Change this constructor 
    this.wheels = 4; 
    this.seats = 1; 
    this.engines = 1; 
}; 

//Try it out here 
var myCar = function(wheels, seats, engines) { 
    this.wheels = wheels; 
    this.seats = seats; 
    this.engines = engines; 
}; 
var myCar = new Car(6, 3, 1); 
+0

我想填寫代碼根據指定的說明。鏈接http://www.freecodecamp.com/challenges/make-unique-objects-by-passing-parameters-to-our-constructor#?solution=var%20Car%20%3D%20function()%20%7B% 0A%20%20%2F%2FChange%20this%20constructor%0A%20%20this.wheels%20%3D%204%3B%0A%20%20this.seats%20%3D%201%3B%0A%20% 20this.engines%20%3D%201%3B%0A%7D%3B%0A%0A%2F%2FTry%20IT%20out%20here%0Avar%20myCar%3B%0A –

+0

您的指示滿足您的第一個代碼片斷。所以,請您在使用第一個'Car'構造函數時向我們展示什麼是指令失敗。 – tenbits

+0

你想要'新車(3,1,2)'總是返回** **相同​​*對象的引用嗎? – tenbits

回答

1

編碼挑戰的回答對您所添加的鏈接:

var Car = function(wheels, seats, engines) { 
if(isNaN(wheels)) 
    wheels = 0; 
if(isNaN(seats)) 
    seats = 0; 
if(isNaN(engines)) 
    engines = 0; 
    this.wheels = wheels; 
    this.seats = seats; 
    this.engines = engines; 
}; 
//Try it out here 
var myCar = new Car(2,6,3); 
myCar = new Car(3,1,2); 
myCar = new Car(4,4,2); 

添加此代碼後運行測試。 - 所有將通過

+0

是的,它也可以。感謝解決方案。 –

1

你已經回答了你自己:

var Car = function(wheels, seats, engines) { 
    //additional checks 
    if(isNaN(wheels)) 
     wheels = 0; 
    if(isNaN(seats)) 
     seats = 0; 
    if(isNaN(engines)) 
     engines = 0; 
    this.wheels = wheels; 
    this.seats = seats; 
    this.engines = engines; 
}; 

//Try it out here 
var myCar = new Car(3,1,2); 
console.dir(myCar); 

myCar = new Car(4,4,2); 
console.dir(myCar); 

myCar = new Car(2,6,3); 
console.dir(myCar); 
+0

是的,它完成了。感謝解決方案。 –

相關問題