zilongxuan001 / LearnFreecode

0 stars 0 forks source link

Make Instances of Object with a Constructor Function #276

Open zilongxuan001 opened 6 years ago

zilongxuan001 commented 6 years ago

介绍

为了使用constructor function,需要加一个关键词new

275

var myCar = new Car();

现在myCar就是Car的一个示例,内容如下

{
  wheels: 4,
  engines: 1,
  seats: 5
}

注意,调用constructor时,一定要加new

实例instance一旦创造出,就可以像对象一样增删改查其属性,如

myCar.turboType = "twin";

现在变量myCar有一个属性turboType,和值twin

练习

In the editor, use the Car constructor to create a new instance and assign it to myCar.

Then give myCar a nickname property with a string value.

代码


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

// Only change code below this line.

var myCar=new Car();
myCar.nickname = "fat boy";

结果显示

image

来源

https://www.freecodecamp.org/challenges/make-instances-of-objects-with-a-constructor-function