这在另一个对象的事件处理程序中

编程入门 行业动态 更新时间:2024-10-27 06:34:15
本文介绍了这在另一个对象的事件处理程序中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

这在另一个对象的事件处理程序中

本文发布于:2023-11-09 15:03:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572679.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:这在   对象   事件   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!