In regards to the below shim why did the author put var F outside of the anonymous function(o) and create a closure. Wouldn't var F inside of function(o) have worked also?
Thank you.
Code:
if (typeof Object.create != 'function') {
(function () {
// why is this outside of Object.Create.
var F = function () {};
Object.create = function (o) {
if (arguments.length > 1) { throw Error('Second argument not supported');}
if (o === null) { throw Error('Cannot set a null [[Prototype]]');}
if (typeof o != 'object') { throw TypeError('Argument must be an object');}
F.prototype = o;
return new F;
};
})();
}
If F were declared in the Object.create function, a new version of F would be created each time Object.create is called. With F declared outside Object.create, the same F will be used each time Object.create is called.
The semantics (of F inside vs. outside) are technically different, but in practicality I don't see any difference, except as Jeff Mott mentioned the performance issue. Where'd you find this code?
Last edited by handcraftedweb; 06-01-2012 at 12:24 PM.
Does the below code produce the identical result as the originally posted code?
Thank you.
New Code:
Code:
if (typeof Object.create != 'function') {
(function () {
Object.create = function (o) {
if (arguments.length > 1) { throw Error('Second argument not supported');}
if (o === null) { throw Error('Cannot set a null [[Prototype]]');}
if (typeof o != 'object') { throw TypeError('Argument must be an object');}
//create a new object
var newObject = {};
//set the newObject's prototype.
newObject.prototype = o;
//return newObject
return newObject;
};
})();
}
Original Code
Code:
if (typeof Object.create != 'function') {
(function () {
// why is this outside of Object.Create.
var F = function () {};
Object.create = function (o) {
if (arguments.length > 1) { throw Error('Second argument not supported');}
if (o === null) { throw Error('Cannot set a null [[Prototype]]');}
if (typeof o != 'object') { throw TypeError('Argument must be an object');}
F.prototype = o;
return new F;
};
})();
}
Please ignore the last question. I thought the prototype object was stored in the property prototype but I just learned it's stored in __proto__ which is now deprecated, hence the reason for the original code.
Bookmarks