如何在绑定this
类后访问this
元素?ES6 - 如何在绑定`this`类后访问`this`元素?
例如,如果没有绑定this
:
$(".button-open").click(function(event) {
console.log(this); // <a href="#" class="button-open">Open</a>
this.openMe();
});
随着结合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>
再结合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));
结合后:
$(".element").animate({}, 'fast', 'swing', function(event) {
console.log(this); // undefined
}.bind(this));
任何全球或防弹方式再次获得element
的?
着我们通过event.tar访问得到? – Geeky
通过再次使用jQuery选择器? – Li357
@Geeky是的点击,但不是为动画,请参阅我上面的编辑。 – laukok