Skip to content

Instantly share code, notes, and snippets.

@samuelluis
Last active August 21, 2016 18:16
Show Gist options
  • Save samuelluis/5e89135b961e8ef6204ea5bd788257ea to your computer and use it in GitHub Desktop.
Save samuelluis/5e89135b961e8ef6204ea5bd788257ea to your computer and use it in GitHub Desktop.
var Wrapper = function(obj){
if(obj == null) obj = {};
Object.defineProperty(this, "__value__", {
enumerable: false,
configurable: true,
writable: false,
value: obj
});
do {
var props = Object.getOwnPropertyNames(obj);
for(prop of props){
var opts = Object.getOwnPropertyDescriptor(obj, prop);
if(opts.value){
var val = this.__value__[prop];
if(val.typeof(Function)) opts.value = val.bind(this.__value__);
else opts.value = val;
}
try{ Object.defineProperty(this, prop, opts); } catch(err){}
}
} while (obj = Object.getPrototypeOf(obj));
};
Object.defineProperty(Object.prototype, "wrap", {
enumerable: false,
configurable: true,
writable: false,
value: function () {
this.__proto__ = new Wrapper(this);
return this;
}
});
@samuelluis
Copy link
Author

samuelluis commented Aug 18, 2016

Wrap any type into a Custom Type with all properties and functions from Original Type. e.g. num = new Wrapper(9) then num.toFixed() //-> "9".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment