Last active
December 21, 2015 14:08
-
-
Save akira-cn/6317012 to your computer and use it in GitHub Desktop.
ES 6 实现PHP的魔术方法 —— 可以在比较新的Firefox下试试~
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
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
真是高级啊