0

I have problem understanding creating object with Object.creat(Person.prototype) and new Person().

I am learning from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create, in which the section "Using propertiesObject argument with Object.create()" said

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

And I wrote a piece of code as below to get to know more details. Would you like to explain a bit for me? Thank you all:).

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 is directly created by original constructor and person2 seems to be created by Person.prototype object, but I think it will finally refer to the constructor and be created by the constructor as person1. However, person1 has 'name' property while person2 doesn't. So what's the difference between the two object creation and what happens behind? Thanks very much.

Junlong Wang
  • 418
  • 4
  • 13
  • 4
    `Object.create(Person.prototype)` never calls `Person`, thus `this.name = "AAA"` is never executed, thus no `name` property exists. As the comment says: _“Of course, if there is actual initialization code in the Constructor function, the `Object.create()` cannot reflect it”_. – Sebastian Simon Dec 20 '16 at 00:50
  • `var person1 = new Person();` is like doing `var person1 = Object.create(Person.prototype); Person.call( person1 );` – Paul Dec 20 '16 at 01:02
  • 1
    Please heed the [*MDN notes*](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/proto) regarding the use of `__proto__` (i.e. don't). Use [*Object.getPrototypeOf*](http://ecma-international.org/ecma-262/7.0/index.html#sec-object.getprototypeof). – RobG Dec 20 '16 at 01:05
  • @Xufox Thanks for your reply. If Person is not called, why person1.constructor === person2.constructor is true? – Junlong Wang Dec 20 '16 at 02:12

0 Answers0