Skip to content

Instantly share code, notes, and snippets.

@akira-cn
Last active December 21, 2015 14:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akira-cn/6317012 to your computer and use it in GitHub Desktop.
Save akira-cn/6317012 to your computer and use it in GitHub Desktop.
ES 6 实现PHP的魔术方法 —— 可以在比较新的Firefox下试试~
<meta charset="utf-8">
<script>
function MagicObject() {
return new Proxy(this, {
get: function (target, name) {
if (name in target) {
return target[name];
} else {
var ret = function(){
if('__call' in target){
return target.__call(target, name);
}
}
ret.toString = function(){
'[not implemented]'
}
return ret;
}
}
});
}
var obj = new MagicObject();
obj.__call = function(target, name){
alert('调用了魔术方法:' + name);
if(name == 'a'){
return 'hello world';
}
}
obj.c = function(){
return '没有调用魔术方法:c';
}
alert(obj.a());
alert(obj.b());
alert(obj.c());
alert(typeof obj.e);
</script>
@welefen
Copy link

welefen commented Aug 23, 2013

真是高级啊

@miller
Copy link

miller commented Aug 23, 2013

高端大气上档次

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