Understanding Crockford's Object.create shim

后端 未结 5 1515
后悔当初
后悔当初 2020-11-28 14:44

I\'ve been reading up on the Crockford shim for preventing the overwriting of prototypes, and understand that it\'s not the end-all/be-all solution at times. I also underst

5条回答
  •  Happy的楠姐
    2020-11-28 15:18

    if (typeof Object.create !== 'function') {
        Object.create = function (o) {
            function F() {}
            F.prototype = o;
            return new F();
        };
    }
    var oldObject={prop:'Property_one' }; // An object
    var newObject = Object.create(oldObject); // Another object
    

    In the above example we've created a new object newObject using create method which is a member function of Object object that we've added in the Object object earlier in our (Crockford's) example. So basically what it does is that, the create method declares a function F, an empty object every function is a first class object in javascript and then we've inherited the prototype of o (in that case o is also an object oldObject passed as the parameter of create method) and finally we've returned the new object (an instance of F) using return new F(); to the variable newObject, so now newObject is an object that inherited the oldObject. Now if you write console.log(newObject.prop); then it'll output Property_one because our newObject object has inherited the oldObject and that's why we've got the value of prop as Property_one. this is known as prototypical inheritance.

    You must pass an object as the parameter of create method

提交回复
热议问题