You did n’t know about JavaScript series (55)-Object.create ()

[[Prototype]] Mechanism is an internal connection that exists in an object, it will refer to other objects. The role of this link: If the required attributes and methods are not found on the object, the engine will continue to search on the [[Prototype]] associated object. Similarly, if the required reference is not found in the latter, it will continue to search for its [[Prototype]], and so on. The link of this series of objects is called the "prototype chain"
 
var foo = {
  something: function() {
    console.log('Tell me something good...');
  }
}

var bar = Object.create(foo);
bar.something(); // Tell me something good...

Object.create () will create a new object bar and associate it with the object foo we specified, so that we can give full play to the power of the [[Prototype]] mechanism and avoid unnecessary troubles (such as using the new constructor call Will generate .prototype and .constructor)

 

We don't need a class to create a relationship between two objects, we only need to associate objects through delegation. And Object.create (...) does not contain any kind of tricks, so it can perfectly create the relationship we want.

 

Object.create (...) is a new function in ES5, so in the environment before ES5, if you want to support this function, you need to use a simple polyfill code, which partially implements Object.create (... ) Features
if(!Object.create){
  Object.create = function(o) {
    function F(){}
    F.prototype = o;
    return new F();
  }
}

 

Guess you like

Origin www.cnblogs.com/wzndkj/p/12730481.html