请看下面的代码片段,
我有一个方法someFunc
Javascript类someClass
在方法定义内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,如果没有绑定,它指的是按钮元素。
我的问题是:如何同时获得两者?因为我想在处理程序内部SomeClass
类的某些属性
访问事件正在冒泡的元素(目标(或当前元素(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类。
只需将上下文保存在外部函数中:
SomeClass.prototype.someFunc = function(){
let _this = this;
var btn = document.crealeElement("button");
btn.onclick = function() {
_this.somePropertyOfSomeClass = true; //saved context
this.classList.add("active");
}
}
将此代码this.classList.add("active");
替换为btn.setAttribute("class", "active");
SomeClass.prototype.someFunc = function(){
var btn = document.crealeElement("button");
btn.onclick = function() {
this.somePropertyOfSomeClass = true; //this works, because bind
btn.setAttribute("class", "active"); //this may be help you
}.bind(this);
}
这样的事情应该可以工作:
SomeClass.prototype.someFunc = function(){
var that = this;
var btn = document.crealeElement("button");
btn.onclick = function() {
that.somePropertyOfSomeClass = true; //references of SomeClass because of the closure
this.classList.add("active"); //this should reference btn
};
}
另请参阅@Dominic的帖子,这是一个更好的解决方案。