问题描述
A类(我的)实现了B类(第三方)的事件处理程序。在这些事件处理程序中,我想访问A类的属性。
在A类的处理程序中使用 this 不起作用,因为它引用了B类范围。
全局变量似乎是唯一的选择。我错过了一个更好的选择吗?
另一个解决方案是将事件处理程序绑定到您的对象!
首先需要将 bind
方法添加到任何函数对象。使用此代码:
Function.prototype.bind = function(scope){
var func = this;
return function(){
return func.apply(scope,arguments);
}
}
现在您可以注册 B类
这种方式的 A类
方法的事件处理程序:
var a = new A();
var b = new B();
b.registerEvent(a.eventHandlerMethod.bind(a));
这样任何对这个
的引用都在代码 A.eventHandlerMethod
将指向对象 a
。
http:// www .alistapart.com / articles / getoutbindingsituations /
另一篇文章:
Class A (mine) implements event handlers for class B (3rd party). Within these event handlers, I would like to access class A's properties.
Using this in class A's handlers does not work because it references class B's scope.
Global variables seem like the only option. Am I missing a better alternative?
Another solution is to bind your event handlers to your object!
You first need the add the bind
method to any function object. Use this code:
Function.prototype.bind = function(scope) {
var func = this;
return function() {
return func.apply(scope, arguments);
}
}
Now you can register your class B
event handlers to your class A
methods this way:
var a = new A();
var b = new B();
b.registerEvent(a.eventHandlerMethod.bind(a));
This way any references to this
within the code of A.eventHandlerMethod
will point to object a
.
If you need a deeper understanding of this stuff you can read this great article: http://www.alistapart.com/articles/getoutbindingsituations/
Another article: http://alternateidea.com/blog/articles/2007/7/18/javascript-scope-and-binding
这篇关于这在另一个对象的事件处理程序中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!