调用函数时“this”的行为bar
让我感到困惑。请参阅下面的代码。当从点击处理程序调用 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);
}