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 / articles / getoutbindingsituations /另一篇文章: alternateidea/blog/articles/2007/7/18/javascript-scope-and-binding
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: www.alistapart/articles/getoutbindingsituations/
Another article: alternateidea/blog/articles/2007/7/18/javascript-scope-and-binding
更多推荐
这在另一个对象的事件处理程序中
发布评论