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

object created with "new" keywords and the object created with "Object.create" gives different result

本文关键字:对象 创建 结果 create 关键字 new 使用 Object      更新时间:2023-09-26

谁能向我解释为什么使用"new"关键字创建的对象和使用"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

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

var car = new Car();

和:

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

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

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

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

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