通过将参数传递给构造函数来创建唯一对象

时间:2016-03-11 10:01:31

标签: javascript jquery constructor

通过将参数传递给构造函数来创建唯一对象

我们拥有的构造函数很棒,但是如果我们不总是想创建相同的对象呢?

要解决这个问题,我们可以在构造函数中添加参数。我们这样做如下例所示:

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以使用parameterswheels, 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)应生成一个wheels的对象 属性3,seats属性为1,engines属性为2.

  • 调用new Car(4,4,2)应生成一个wheels的对象 属性为4,seats属性为4,engines属性为2.

  • 调用new Car(2,6,3)应生成一个wheels的对象 属性为2,seats属性为6,engines属性为3.

  • 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);

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);

答案 1 :(得分: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);

添加此代码后运行测试。 - 一切都会通过