在每次调用对象时使用相同的功能 [英] use same function in every call of object

查看:65
本文介绍了在每次调用对象时使用相同的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在js中的Ive对象

var myobj = {} 

我需要每次你调用方法,如 myObj.a()
myObj.b()等,它将调用相同的功能,并且不会调用任何其他...

I need that every time that you called to method in method like myObj.a() or myObj.b() etc it will call to the same function and will not call to anything else at all...

like myFn = function(){
return 1 + 1 ;
} 


推荐答案

它是ES6,我不相信它可以被pollyfilled所以没有IE支持我很害怕。如你所说,这不是一个问题,所有的都很好。

It is ES6 and i do not believe it can be pollyfilled so no IE support I'm affraid. As you said thats not an issue then all good.

var obj = {};

var objProxied = new Proxy(obj, {
  get: (target, key, reciever) => {
    console.log(`Handler hit, looking for prop ${key}`);
    return (...args) => foo(...args); // return what ever you like here
  }
});

基本上它的工作原理是向代理提供要被代理的对象,处理程序。 MDN列出所有不同的处理程序,如果您不提供处理程序,那么它将调用对象。

Essentially how it works is you provide the proxy with the object to be 'proxied' and a map of handlers. The MDN lists all the different handlers, if you do not provide a handler then it will call down unto the object.

您的处理程序提供了不同的东西,具体取决于处理程序。在我们的例子中, get 接收被调用的对象,原始的 obj 和属性名。

Your handler is provided different things depending on the type of handler. In our case the get receives the object its being called upon, the original obj and the property name.

重要的是要注意,您的处理程序必须返回一个值(在示例中为该注释的位置),如果不这样做将调用底层对象。这将导致我们的示例中的异常,因为我们将尝试执行一个未定义的方法。

It is important to note your handler must return a value, (where the comment is in the example) if you do not it will call down to the underlying object. This would cause an exception in our example as we would try to execute an undefined method.

MDN

在行动中:

var obj = {};

function foo(...args) {
  console.log('foo called With:', ...args);
}

var objProxied = new Proxy(obj, {
  get: (target, key, reciever) => {
  	console.log(`Handler hit, looking for prop ${key}`);
    return (...args) => foo(...args)
  }
});

objProxied.a(10);
objProxied.b(20, 50);

这篇关于在每次调用对象时使用相同的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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