Last active
August 29, 2015 14:06
-
-
Save samshull/fe4ea1f14396387f4f6d to your computer and use it in GitHub Desktop.
simplifying method_missing functionality with Proxy
This file contains 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
var root = (function(){ return this; })(); | |
function ProxyClass() { | |
if (this === root) throw Error(); | |
var instance = this; | |
return Proxy.create({ | |
get: function(receiver, name) { | |
console.log('get', name); | |
return instance[name] || (instance._get && instance._get(name, receiver)) || undefined; | |
}, | |
set: function(receiver, name, value) { | |
console.log('set', name, value); | |
if (instance._set) { | |
return instance._set(name, value, receiver) !== false; | |
} | |
instance[name] = value; | |
return true; | |
}, | |
has: function(name) { | |
console.log('has', name); | |
return name in instance || (instance._has && instance._has(name)); | |
}, | |
hasOwn: function(name) { | |
console.log('hasOwn', name); | |
return instance.hasOwnProperty(name) || (instance._hasOwn && instance._hasOwn(name, value, receiver)); | |
} | |
}, instance); | |
} | |
ProxyClass.prototype = { | |
_get: function(name) { | |
console.log('class get'); | |
return this[name]; | |
}, | |
_set: function(name, value) { | |
console.log('class set'); | |
this[name] = value; | |
}, | |
_has: function(name) { | |
console.log('class has'); | |
return name in this; | |
}, | |
_hasOwn: function(name) { | |
console.log('class hasOwn'); | |
return Object.hasOwnProperty(name); | |
} | |
}; | |
var proxy = ProxyClass(); | |
console.log('first', proxy.first); | |
proxy.first = 123; | |
console.log('first2', proxy.first); | |
console.log('toString', proxy.toString()); | |
console.log('proxy instanceof ProxyClass', proxy instanceof ProxyClass); | |
console.log(Object.prototype.toString.call(proxy)); | |
function InheritProxy() { | |
return ProxyClass.apply(this, arguments); | |
} | |
InheritProxy.prototype = Object.create(ProxyClass.prototype); | |
InheritProxy.prototype._get = function(name) { | |
console.log('subclass get'); | |
return this[name]; | |
}; | |
var subproxy = new InheritProxy(); | |
console.log('sfirst', subproxy.first); | |
subproxy.first = 123; | |
console.log('sfirst2', subproxy.first); | |
console.log('toString', subproxy.toString()); | |
console.log('subproxy instanceof InheritProxy', subproxy instanceof InheritProxy); | |
console.log('subproxy instanceof ProxyClass', subproxy instanceof ProxyClass); | |
console.log(Object.prototype.toString.call(subproxy)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment