我一直在阅读 Crockford 垫片以防止覆盖原型,并了解它有时不是最终/全部解决方案。我也明白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.
这样,当我们将东西扩充到“another_stooge”时,“stooge”对象的原型就不会被覆盖。无需使用 'constructor' 重置 'stooge' 原型。
提前致谢,
-k