関数bar
が呼び出されたときの "this"の動作は私を困惑させます。以下のコードを参照してください。 barがhtml要素ではなくクリックハンドラから呼び出されたときに、 "this"が普通の古いjsオブジェクトインスタンスになるように手配する方法はありますか?jQuery/JavaScript "this"ポインタの混乱
// 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);
}
この「fooインスタンスです」と説明してください。次のjsfiddle(http://jsfiddle.net/yY6fp/1/)は 'this.bar()'の 'this'が' window'(グローバル)オブジェクトを評価することを示しています。 –