zilongxuan001 / LearnFreecode

0 stars 0 forks source link

Construct JavaScript Object with Functions #275

Open zilongxuan001 opened 6 years ago

zilongxuan001 commented 6 years ago

介绍

274 变量构造对象

可以用constructor function(构造函数)来创造对象。

方法

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

constructor里,this变量指构造器构造的新对象。

this.wheels = 4 就是给属性wheels增加一个值4

你也可以把构造器作为它要创造的对象的描述。

练习

Have your MotorBike constructor describe an object with wheels, engines and seats properties and set them to numbers.

代码


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

// Only change code below this line.

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

};

结果显示

image

来源

https://www.freecodecamp.org/challenges/construct-javascript-objects-with-functions

zilongxuan001 commented 6 years ago

注意对比 变量构造对象的形式

var car = {
  "wheels":4,
  "engines":1,
  "seats":5
};