bar
调用函数时“this”的行为让我感到困惑。请参阅下面的代码。当从单击处理程序调用 bar 而不是 html 元素时,有什么方法可以将“this”安排为一个普通的旧 js 对象实例?
// 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);
}