傳遞參數給我們的構造使唯一對象:傳遞參數給我們的構造使唯一對象
我們構造函數是偉大的,但如果我們不總是要創建同一個對象是什麼?
要解決這個問題,我們可以將參數添加到我們的構造函數中。我們這樣做是類似於下面的示例:
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
屬性的屬性engines
和engines
屬性的2.調用
new Car(2,6,3)
應該產生一個對象爲2的wheels
屬性,爲6的seats
屬性,和爲3engines
屬性。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);
我想填寫代碼根據指定的說明。鏈接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 –
您的指示滿足您的第一個代碼片斷。所以,請您在使用第一個'Car'構造函數時向我們展示什麼是指令失敗。 – tenbits
你想要'新車(3,1,2)'總是返回** **相同*對象的引用嗎? – tenbits