【发布时间】:2010-10-17 04:02:52
【问题描述】:
当函数bar 被调用时“this”的行为让我很困惑。请参阅下面的代码。当从点击处理程序调用 bar 时,有没有办法将“this”安排为普通的旧 js 对象实例,而不是 html 元素?
// a class with a method
function foo() {
this.bar(); // when called here, "this" is the foo instance
var barf = this.bar;
barf(); // when called here, "this" is the global object
// when called from a click, "this" is the html element
$("#thing").after($("<div>click me</div>").click(barf));
}
foo.prototype.bar = function() {
alert(this);
}
【问题讨论】:
-
请解释
"this" is the foo instance。以下 jsfiddle(jsfiddle.net/yY6fp/1) 演示了this.bar()中的this计算结果为window(global) 对象。
标签: javascript jquery this