我一直在阅读克罗克福德垫片以防止重写原型,并了解它并不是最终所有/全部解决方案。我也明白ES5 Shim可能是一个可行的替代方案。我也读this post which provides a more robust, secure alternative。了解克罗克福德的Object.create垫片
不过,我想知道他的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.
这样,“跟屁虫”对象的原型不能当我们加强东西“another_stooge”覆盖。无需使用“构造函数”重置“stooge”原型。
由于提前,
-k
阿!我想我明白了。谢谢谢赫......您的帮助非常感谢! – kaidez 2012-04-13 14:20:45
你是最好的:-) – 2012-04-13 14:25:35