在 PHP 中,即使方法不存在,您也可以使用“神奇”__call
函数检测何时调用该方法。
public function __call($methodName, $args)
{
// do something
}
您可以调用任何方法,名称和参数都会传递给这个神奇的包罗万象的方法。
JavaScript 中是否有类似的技术允许调用任何方法,即使该方法实际上不存在于对象上?
var foo = (function () {
return {
__call: function (name, args) { // NOT REAL CODE
alert(name); // "nonExistent"
}
}
}());
foo.nonExistent();
最佳答案
使用 ES6 可以 Proxy API :
var myObj = {};
var myProxy = new Proxy(myObj, {
get: function get(target, name) {
return function wrapper() {
var args = Array.prototype.slice.call(arguments);
console.log(args[0]);
return "returns: " + args[0];
}
}
});
console.log(myProxy.foo('bar'));
浏览器兼容性可在MDN上获得。截至 2017 年 8 月,除 Internet Explorer 之外的所有浏览器(包括 Microsoft Edge)都支持它。
参见this answer更完整地了解 Proxy。
关于PHP __call 的 JavaScript 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10226064/