Javascript从事件处理程序中获取对父对象/类的引用

编程入门 行业动态 更新时间:2024-10-27 20:27:55
本文介绍了Javascript从事件处理程序中获取对父对象/类的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个类(或包含函数的对象;我听说没有像JavaScript类一样的东西),名为Foo,带有附加到点击事件的事件处理程序。当调用事件处理程序时,我想修改我的类Foo的属性。通常,我将使用 this 关键字,但在事件处理程序中, this 引用设置为引用html元素。这是我的代码:

function Foo(){ this.num = 0; $('element')。click(this.eventHandler); // jQuery将onclick事件附加到我的元素。 this.eventHandler = function(){ this.num ++; //这不工作。 //通常,this指的是我的Foo实例, //但是作为事件处理程序,this指的是html元素。 } }

所以我的问题是:我的实例Foo进入我的事件处理程序,以便我可以修改其属性(如 num )?

function Foo(){ var _self = this; this.num = 0; $('element')。click(this.eventHandler); // jQuery将onclick事件附加到我的元素。 this.eventHandler = function(){ _self.num ++; } }

使用引用 _self =此在外部范围

中定义

I have a class (or function-containing object; I've heard that there is no such thing as a Javascript class) called Foo, with an event handler that is attached to a click event. When the event handler is called, I want to modify a property of my class Foo. Normally, I would use the this keyword, but in the event handler, the this reference is set to the reference to the html element. Here is my code:

function Foo() { this.num=0; $('element').click(this.eventHandler);// jQuery to attach an onclick event to my element. this.eventHandler=function() { this.num++;// This doesn't work. // Normally, "this" would refer to my instance of Foo, // but as an event handler, "this" refers to the html element. } }

So my question is: how do I get a reference to my instance of Foo into my event handler so that I can modify its properties (like num)?

解决方案

function Foo() { var _self = this; this.num=0; $('element').click(this.eventHandler);// jQuery to attach an onclick event to my element. this.eventHandler=function() { _self.num++; } }

use a reference _self = this defined in the outer scope

更多推荐

Javascript从事件处理程序中获取对父对象/类的引用

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

发布评论

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

>www.elefans.com

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