Object.create () exploration

In recent time frame to see the source code and found that when the author (or Contributors) to create objects, inheritance or do when, like to use Object.create ().

MDN on this first method described very clearly,

Object.create(proto[, propertiesObject])

The first parameter passed to an object, (ps: [] is optional), MDN interpretation as a "prototype object newly created object," general pass xx.prototype, if the direct object is, and will be more nested layer __proto__ , eg:

var o = Object.create({},{
    a:{
           writable:true,
        configurable:true,
        value:'1'
    }
})
console.log(o)

You can see the following, because __proto__ implicitly points to the prototype prototype object constructor, if not directly transmitted xx.prototype following problem.
Here Insert Picture Description

The second parameter is propertiesObject is to be added to the newly created object may be enumerated attribute (i.e., its own defined properties, rather than the enumerated attribute on the prototype chain) attribute descriptor object and the corresponding attribute name. These properties correspond Object.defineProperties () of the second parameter. What can enumerate specific attributes, you can go check defineProperties () The second parameter of this method, generally have a value value value value is the last of our object, other property-related configuration parameters, such as read and write it Category.

Once you understand the above, the use of Object.create a very important reason is that we can create a "clean" objects through create (null).
eg:
Here Insert Picture Description
After passing null, the newly created object has no properties. Do not worry about the custom attributes to overwrite the prototype chain. eg, we customized a target, want to check a.hasOwnProperty property, a.toString property, if we use {} to create, you can not directly through a.toString, a.hasOwnProperty direct access, because the property would interfere with the prototype, If you want to check toString property, we are before a Object.prototype.hasOwnProperty.call (a, 'toString') to do the check, in such a way that is troublesome and a waste of a little performance, for in the traversal of the school needs to be done experience. (Of course, you can use Object.keys)

Use will depend on the scenario, unless very clean and highly customizable object (null even after the transfer can not be called an object that can be called a data dictionary, because there is no way to share the inheritance of the Object), no person or use {it} .

Guess you like

Origin www.cnblogs.com/zhangmingzhao/p/11347789.html