Object.create (XXX) and new XXX () function to create a difference

Object.create ( proto, [ propertiesObject ] ) 

The first parameter is the prototype of the newly created object, the second optional parameter, the parameter object is a set of attribute values ​​with the attribute name of the property of the object name of the object will be newly created, the value of a property descriptor (as these structures and attribute descriptor Object.defineProperties () of the second parameter). Note: This parameter object can not be undefined, the only other enumerable properties of the object itself has to be effective, that is to say on the prototype chain of the object attribute is invalid.

First, look at what they have done?

new XXX()

was F = function () {};
was f = new F ();

1. Create an empty object: var obj = new Object ();

2 __proto__ object points to the new constructor prototype: obj .__ proto__ = F.prototype;

3 The scope constructor is assigned to the new object (that is, this points to the new object)

4 execution code constructor (add the new object property)

5 returns the new object

Equivalent to the code:

var Obj = {};
Obj._proto_ =  Person.prototype();
Person.call(Obj);

Object.create(XXX)

Object.create(Base);

1 Create an empty function;

function prototype 2 Base point function;

3 new instance of a function (i.e. so that this example is the prototype function F _proto_ point, i.e. Base function, and finally return to the examples)

Note that the argument passed Base is an object. If a constructor is passed, then the instance can not be inherited.

Equivalent to the following code:

Object.create =  function (Base) {
    var F = function () {};
    F.prototype = Base;
    return new F();
};

 Example 1:

After new, o1 Base with all the attributes, the value 2 is o1.a; Object.create incoming parameter is due to the constructor, o2 is not directed to the Base _proto_, o2 is apparent from the above step is itself a constructor to instantiate an empty out, does not have a property, the output undefined.
 
Example 2:

It can be seen at this time to find a property of the prototype chain o2, o2 of _proto_ (prototype chain) points to the Base2 are looked up, so that access to a property value of 1.

 

 

Original: https://www.jianshu.com/p/165cb07b9de0

Guess you like

Origin www.cnblogs.com/xjy20170907/p/11766234.html