в следующем примере, чтобы отправить в качестве параметра объект «lostThis» метода «instObj», «this» - это оконный объект.Сохраните это в методе, переданном по ссылке
var obj = function() {};
obj.prototype.lostThis = function() {
console.log('lostThis', this instanceof obj, this);
};
var instObj = new obj;
var caller = {
runFn: function(fn) {
fn();
}
};
caller.runFn(instObj.lostThis);
Консоль ответа:
lostThis false Window
В следующем примере (чуть более сложным) существуют различные способы, чтобы вызывать методы «instObj», где это то же самое, и другие где я могу сохранить «этот» объект.
var obj = function() {};
obj.prototype.methodRefHasThis = function() {
var t = this;
return function() {
console.log('methodRefHasThis ', t instanceof obj, t);
};
};
obj.prototype.methodRefLostThis = function() {
console.log('methodRefLostThis ', this instanceof obj, this);
};
obj.prototype.methodRefMaybeThis = function() {
console.log('methodRefMaybeThis ', this instanceof obj, this);
};
var instObj = new obj;
var caller = {
runFn: function(fn) {
fn();
}
};
// width jQuery
$('button')
.bind('click', instObj.methodRefHasThis())
.bind('click', instObj.methodRefLostThis);
caller.runFn(instObj.methodRefHasThis());
caller.runFn(instObj.methodRefLostThis);
caller.runFn(function() {
instObj.methodRefMaybeThis();
});
Console Ответ:
methodRefHasThis true obj
methodRefLostThis false Window
methodRefMaybeThis true obj
methodRefHasThis true obj
methodRefLostThis false <button>press here</button>
Я понимаю, что это происходит с JQuery, чтобы назначить метод к событию, но не мог я вызвать метод "methodRefLostThis" не проигрывают " этот «объект, который будет передан по ссылке?
благодаря
Решение по @am_not_i_am, @Dan_Davies_Brackett и @Ben_Lee
var obj = function() {};
obj.prototype.lostThis = function() {
console.log('lostThis', this instanceof obj, this);
};
var instObj = new obj;
var caller = {
runFn: function(fn) {
fn();
}
};
caller.runFn(instObj.lostThis.bind(instObj));
caller.runFn($.proxy(instObj.lostThis, instObj));
Консоль ответа:
lostThis true obj
lostThis true obj
Woops! Благодарим за редактирование @andres descalzo. –