如何访问 this
绑定(bind)后的元素 this
类(class)?
例如不绑定(bind)this
:
$(".button-open").click(function(event) {
console.log(this); // <a href="#" class="button-open">Open</a>
this.openMe();
});
有绑定(bind)this
:
$(".button-open").click(function(event) {
console.log(this); // Polygon {windowHeight: 965, scrollNum: 0}
this.openMe();
}.bind(this));
如何获取和访问 <a href="#" class="button-open">Open</a>
绑定(bind)后再次this
?
完整代码:
class Polygon {
constructor() {
this.windowHeight = $(window).height();
this.scrollNum = 0;
}
// Simple class instance methods using short-hand method
// declaration
init() {
var clickMe = this.clickMe.bind(this);
return clickMe();
}
clickMe() {
$(".button-open").click(function(event) {
console.log(this);
this.openMe();
}.bind(this));
$(".button-close").click(function(event) {
this.closeMe();
}.bind(this));
}
openMe() {
console.log(this.scrollNum); // 0
this.scrollNum = 200;
console.log(this.scrollNum); // 200
return false;
}
closeMe() {
console.log(this.scrollNum); // 200
return false;
}
}
export { Polygon as default}
有什么想法吗?
编辑:
jQuery 同样的问题 animate
:
$(".element").animate({}, 'fast', 'swing', function(event) {
console.log(this); // the element
}.bind(this));
绑定(bind)后:
$(".element").animate({}, 'fast', 'swing', function(event) {
console.log(this); // undefined
}.bind(this));
获取 element
的任何全局或防弹方式又是?
最佳答案
1. 最好的选择是将上下文存储在变量中并且不要覆盖this
:
var context = this;
$('.element').on('click', function(event) {
// context would be the this you need
// this is the element you need
});
2. 如果您只针对单个元素,则可以从上面执行相反的操作,将要绑定(bind)处理程序的元素保存到一个变量中,然后在其中使用该变量处理程序:
var el = $('.element');
el.on('click', function(event) {
// use el here
}.bind(this));
由于您使用 ES6 标记了问题,因此最好将上下文与 arrow function 绑定(bind)因为使用 bind更冗长,还创建了一个附加功能:
var el = $('.element');
el.on('click', (event) => {
// this is the same as in the outer scope
// use el here
});
3. 另一种选择是使用 target事件对象的属性,但这也可以是元素中的任何子元素(目标是调度事件的元素,而不是绑定(bind)处理程序的元素),因此可能需要遍历 DOM 树才能找到元素你需要,但效率较低。
var el = $('.element');
el.on('click', ({ target }) => {
while (target.parentNode && !target.classList.contains('element')) {
target = target.parentNode;
}
// here the target should be the element you need
});
关于javascript - ES6 - 如何在绑定(bind) `this` 类后访问 `this` 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40815670/