如何在綁定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