用“new”关键字创建的对象和用“Object.create”创建的对象给出不同的结果

时间:2015-02-04 11:23:39

标签: javascript jquery

任何人都可以向我解释为什么使用" "关键字和使用" Object.create "创建的对象关键字给出了不同的结果?

function Car (desc) {
this.desc = 'test';
this.color = "red";
}

Car.prototype.getInfo = function() {
  return 'A ' + this.color + ' ' + this.desc + '.';
}

//if i create object with "new" it's alert "A blue test"
var car =  new Car();
car.color = "blue";
alert(car.getInfo());  //A blue test

// but if i create object with it's alert "A blue undefined"
var car =  Object.create(Car.prototype);
car.color = "blue";
alert(car.getInfo()); //A blue undefined

2 个答案:

答案 0 :(得分:1)

这两段代码(通常)是等价的:

var car = new Car();

var car = Object.create(Car.prototype);
Car.call(car);  // this second line is missing from your code

在您的代码中,构造函数不会运行,因此不会设置这些属性。

答案 1 :(得分:-1)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

Object.create用于继承。 'new'关键字用于创建原型定义的对象实例。

因此,在您的示例中使用Object.create时,它是Car的Prototype而不是Car的实例。

相关问题