Object.creat(Person.prototype)和new Person()之间的区别

时间:2016-12-20 00:48:16

标签: javascript

我在使用Object.creat(Person.prototype)和new Person()创建对象时遇到问题。

我正在学习MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create,其中“使用带有Object.create()的propertiesObject参数”一节说

function Constructor() {}
o = new Constructor();
// is equivalent to:
o = Object.create(Constructor.prototype);
// Of course, if there is actual initialization code in the
// Constructor function, the Object.create() cannot reflect it

我写了一段代码如下,以了解更多细节。 你想为我解释一下吗?谢谢你们:)。

function Person(){
  this.name = "AAA";
}
var person1 = new Person();
var person2 = Object.create(Person.prototype);
alert(person1.constructor ===person2.constructor); // true
alert(person1.__proto__ === person2.__proto__); //true

person1.name; // AAA
person2.name;// undefined

Person1直接由原始构造函数创建,person2似乎是由Person.prototype对象创建的,但我认为它最终会引用构造函数并由构造函数创建为person1。但是,person1具有'name'属性而person2没有。那么两个对象创建和背后发生的事情有什么区别?非常感谢。

0 个答案:

没有答案