【发布时间】:2016-11-26 06:32:50
【问题描述】:
绑定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));
绑定this后如何再次获取和访问<a href="#" class="button-open">Open</a>?
完整代码:
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.target 访问吗?
-
再次使用jQuery选择器?
-
@Geeky 是点击但不是动画,请参阅我上面的编辑。
-
@teelou 我明白了。很难找到一种“防弹”的方式来做到这一点......
-
这是一个荒谬的问题。这就像你在做
elem = x;然后询问如何获得elem的先前值。你不能在 Javascript 中做到这一点。如果你用.bind()覆盖this的值,那么没有通用的方法可以恢复到没有.bind()的this。如果您想访问this中的某些值,那么这完全取决于具体情况。例如,点击处理程序可以访问event.target。没有通用的解决方案。
标签: javascript jquery ecmascript-6 this