A new way to implement the polyfill for javascript Object.create() has left me puzzled. You can find the code here.
if (typeof Object.create != 'function') {
// Implementation steps based on ECMA-262, Edition 5, 15.2.3.5
// Reference: http://es5.github.io/#x15.2.3.5
Object.create = (function() {
// Using a shared constructor to save memory
function Temp() {}
// creating a safe reference to Object.prototype.hasOwnProperty
var hasOwn = Object.prototype.hasOwnProperty;
return function(O) {
// Checking if O is not an object or null
if (typeof O != 'object') {
throw TypeError('Object prototype may only be an Object or null');
}
// Creating a new object with O as its prototype
Temp.prototype = O;
var obj = new Temp();
Temp.prototype = null;
// Adding own properties if present
if (arguments.length > 1) {
var Properties = Object(arguments[1]);
for (var prop in Properties) {
if (hasOwn.call(Properties, prop)) {
obj[prop] = Properties[prop];
}
}
}
return obj;
};
})();
}
- Why does the implementation use IIFE and closure?
- Is there any issue with the simpler logic below, without using IIFE and return function?
if (typeof Object.createOwn != "function") {
Object.createOwn = function(O) {
// Check if O is not an object or null
if (typeof(O) != "object") {
throw TypeError("Object prototype may only be an Object or null");
}
// Create a new object with O as its prototype
var obj;
var Temp = function() {};
Temp.prototype = O;
obj = new Temp();
// Add own properties if present
if (arguments.length > 1) {
var Properties = Object(arguments[1]);
for (var prop in Properties) {
if (Properties.hasOwnProperty(prop)) {
obj[prop] = Properties[prop];
}
}
}
return obj;
}
}
var foo = {
one: 1,
two: 2
};
var bar = Object.createOwn(foo, 3);