Skip to main content
 首页 » 编程设计

javascript之如何在 javascript 成员函数中访问两个 "this"

2025年01月19日19mfryf

请看下面的代码片段,

我有一个 Javascript 类 someClass 的方法 someFunc

在方法定义中 btn 变量的 onclick 处理程序中,我想获得对 SomeClass 和按钮的引用。

SomeClass.prototype.someFunc = function(){ 
 
    var btn = document.crealeElement("button"); 
    btn.onclick = function() { 
       this.somePropertyOfSomeClass = true; //this works, because bind 
       this.classList.add("active"); //this does not 
    }.bind(this); 
} 

我知道,如果我使用 bind(this) 那么点击处理程序中的 this 变量指的是 SomeClass,如果没有绑定(bind),它指的是按钮元素。

我的问题是:如何同时获得两者?因为我想要处理程序中 SomeClass 类的一些属性

请您参考如下方法:

访问事件冒泡通过的元素 (target) 或当前元素 (currentTarget) 是更好、更现代的做法。除了类实例之外,在类中使用 this 是不清楚的。此外,最好使用事件监听器,以便可以附加相同类型的多个事件。

SomeClass.prototype.someFunc = function(){ 
    const btn = document.crealeElement("button"); 
    btn.addEventListener('click', (event) => { 
       this.somePropertyOfSomeClass = true; //this works, because arrow function has lexical scope 
       event.target.classList.add("active"); // proper way to access the element 
    } 
} 

您可能还想看看 ES6 类。