bar
関数が呼び出されたときの「this」の動作は私を困惑させます。以下のコードを参照してください。バーが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);
}