Last active
March 4, 2016 10:39
-
-
Save Mevrael/5b58cb98c3977d456b44 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Native Object.create() does not works with properties if they are objects or arrays. | |
For example, | |
var p = { | |
obj: { | |
one: 1, | |
two: 2 | |
} | |
}; | |
var o = Object.create(p); | |
o.obj.one = 10; // <-- this also changed an original object's property, with this extension, it's fixed | |
console.log(p.obj.one); // prints 10, but 1 was expected. | |
console.log(o.obj.one); // 10 | |
/** | |
* Extends native Object.create() to create also objects from parent object properties if they are objects or arrays | |
* @param {Object} proto | |
* @param {Object} [propertiesObject] | |
* @static | |
* @return {Object} | |
*/ | |
Object.create = function(proto, propertiesObject = null) { | |
if (Array.isArray(proto)) { | |
var o = []; | |
} else { | |
var o = {}; | |
} | |
let properties = Object.keys(proto); | |
for (let k = 0; k < properties.length; k++) { | |
let property_name = properties[k]; | |
if (typeof proto[property_name] === 'object') { | |
o[property_name] = Object.create(proto[property_name]); | |
} else { | |
o[property_name] = proto[property_name]; | |
} | |
} | |
if (propertiesObject !== null) { | |
Object.defineProperties(o, propertiesObject); | |
} | |
return o; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment