Created
July 28, 2012 18:13
-
-
Save dherman/3194234 to your computer and use it in GitHub Desktop.
What everyone kinda wishes Object.create had been
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
Object.beget = (function() { | |
var create = Object.create, | |
defineProperty = Object.defineProperty; | |
// see https://gist.github.com/3194222 | |
var hasOwn = Object.prototype.hasOwnProperty.unselfish(); | |
return function beget(proto, own) { | |
var result = create(proto); | |
var descriptor = { | |
enumerable: true, | |
writable: true, | |
configurable: true | |
}; | |
for (var key in own) { | |
if (!hasOwn(own, key)) | |
continue; | |
descriptor.value = own[key]; | |
defineProperty(result, key, descriptor); | |
} | |
return result; | |
}; | |
})(); | |
var root = { | |
method: function() { return [this.x, this.y] } | |
}; | |
var o = Object.beget(root, { x: 0, y: 22 }); | |
console.log(o.method()); // [0, 22] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When I first started learning about Object.create I actually assumed this was how it worked. I was bewildered when things weren't working as I expected. I do wish this method were simpler.