zilongxuan001 / LearnFreecode

0 stars 0 forks source link

Make Unique Objects by Passing Parameters to our Constructor #277

Open zilongxuan001 opened 6 years ago

zilongxuan001 commented 6 years ago

介绍

如何创造不一样的对象。

方法

constructor里增加parameters

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

当调用constructor时,可以传入arguments

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

这样就创造一个对象如下

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

}

练习

Now give it a try yourself! Alter the Car constructor to use parameters to assign values to the wheels, seats, and engines properties.

Then call your new constructor with three number arguments and assign it to myCar to see it in action.

代码


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

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

结果显示

image

来源

https://www.freecodecamp.org/challenges/make-unique-objects-by-passing-parameters-to-our-constructor