了解Crockford的Object.create垫片

kai*_*dez 10 javascript prototype object-create

我一直在阅读了关于克罗克福德的垫片,以防止原型的改写,并了解它的不是结束,所有的/是的解决办法的时候.我也明白,ES5 Shim可能是一个可行的替代品.我还阅读了这篇文章,它提供了一个更强大,更安全的选择.

不过,我想知道他的Object.create垫片是什么"说"然后"做".如果我的解释评论是正确的,有人可以告诉我吗?

if (typeof Object.create === 'undefined') { 
//If the browser doesn't support Object.create

  Object.create = function (o) {
  //Object.create equals an anonymous function that accepts one parameter, 'o'.

    function F() {};
    //Create a new function called 'F' which is just an empty object.

    F.prototype = o;
    //the prototype of the 'F' function should point to the
    //parameter of the anonymous function.

    return new F();
    //create a new constructor function based off of the 'F' function.
  };
}

//Then, based off of the 'Lost' example in the Crockford book...

var another_stooge = Object.create(stooge);

//'another_stooge' prototypes off of 'stooge' using new school Object.create.
//But if the browser doesn't support Object.create,
//'another_stooge' prototypes off of 'stooge' using the old school method.
Run Code Online (Sandbox Code Playgroud)

这样,当我们将东西增加到'another_stooge'时,'stooge'对象的原型不能被覆盖.无需使用'构造函数'重置'stooge'原型.

提前致谢,

-k

The*_*pha 15

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
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我们newObject使用create方法创建了一个新对象,该方法是我们(Crockford's)示例中早先在对象中Object添加的Object对象的成员函数.所以基本上它的作用是,该create方法声明一个函数F,一个空对象every function is a first class object in javascript,然后我们继承了原型o(在这种情况下o也是一个oldObject作为create方法参数传递的对象),最后我们返回了新的对象(F的一个实例)使用return new F();变量newObject,所以现在newObject是一个继承的对象oldObject.现在,如果你写,console.log(newObject.prop);那么它将输出,Property_one因为我们的newObject对象继承了oldObject,这就是我们得到propas 的值的原因Property_one.这被称为原型继承.

您必须传递一个对象作为create方法的参数