Поведение this при вызове функции bar
сбивает меня с толку. См. Код ниже. Есть ли способ сделать так, чтобы "this" был простым старым экземпляром объекта js, когда bar вызывается из обработчика кликов, вместо того, чтобы быть элементом 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
вthis.bar()
оценивается какwindow
(глобальный) объект. - person Kevin Meredith   schedule 02.01.2014