PHP等效的PHP __call [英] JavaScript Equivalent Of PHP __call

查看:86
本文介绍了PHP等效的PHP __call的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,您可以使用magic __ call 函数检测方法何时被调用,即使它不存在。

In PHP you can detect when a method is called even when it doesn't exist using the "magic" __call function.

public function __call($methodName, $args)
{
    // do something
}

您可以调用任何方法,并将名称和参数传递给此魔法全部。

You can call any method and the name and arguments are passed to this magic catch-all.

JavaScript中是否有类似的技术允许调用任何方法,即使它实际上不存在于对象上?

Is there a similar technique in JavaScript that would allow any method to be called even if it actually didn't exist on the object?

var foo = (function () {
    return {
         __call: function (name, args) { // NOT REAL CODE
             alert(name); // "nonExistent"
         }
    }
}());

foo.nonExistent();


推荐答案

可能使用ES6 代理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]);
    }
  }
});
console.log(myProxy.foo('bar'));  // prints 'bar'

MDN 。截至2017年8月,除Internet Explorer之外的所有浏览器(包括Microsoft Edge)都支持它。

Browser compatibility is available on MDN. As of August 2017 all browsers (including Microsoft Edge) except Internet Explorer support it.

请参阅这个答案可以更全面地了解代理。

See this answer for a more complete look at Proxy.

这篇关于PHP等效的PHP __call的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆