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 understand that ES5 Shim may be a viable alternative to this. I also read this post which provides a more robust, secure alternative.
Still, I'd like to know what his Object.create
shim is "saying" and then "doing." Can someone please tell me if my explanation comments are right?
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.
This way, the prototype of the 'stooge' object can't be overwritten when we augment stuff to 'another_stooge'. No need to reset the 'stooge' prototype using 'constructor'.
Thanks in advance,
-k
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…