Javascript pub/sub implementation works for functions, but not objects' methods

限于喜欢 提交于 2019-12-04 20:11:06

When you pass a.i to PubSub.subscribe, you've "detached" the i function from a, its invocation context. Either use an anonymous function to maintain the binding:

PubSub.subscribe("test", function (x) { a.i(x); });

or use Function.bind to preserve a as this whenever i is called:

PubSub.subscribe("test", a.i.bind(a));

N.B. Function.bind is not supported in all browsers, so you'll want to use the shim.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!