Javascript 含糊不清';这';内部jquery回调
我的问题是jquery回调中“this”的上下文Javascript 含糊不清';这';内部jquery回调,javascript,jquery,Javascript,Jquery,我的问题是jquery回调中“this”的上下文 $('input').on('change', function(){ this.number = $(this).val(); }); 在上面,这是输入元素,通常是我们想要的“this”。问题是,当它成为一个对象的方法时,如下所示 // constructor pattern var View = function(){ this.number = 0; }; // method definition View.protot
$('input').on('change', function(){
this.number = $(this).val();
});
在上面,这是输入元素,通常是我们想要的“this”。问题是,当它成为一个对象的方法时,如下所示
// constructor pattern
var View = function(){
this.number = 0;
};
// method definition
View.prototype.foo = function(){
$('input').on('change', function(){
// former this should be the object instance and
// the latter should be the html element.
this.number = $(this).val();
});
};
View.prototype.foo = function(){
$('input').on('change', function(){
this.number = $(this).val();
}.bind(this)); // bind the callback to the instance of View object
};
View.prototype.foo = function(){
$('input').on('change', function(){
// explicitly set this to be the instance
// while sacrificing generality since code breaks when the object name is not 'view'
view.number = $(this).val();
});
};
var view = new View();
要更改此函数的上下文,可以按如下方式使用function.bind()
// constructor pattern
var View = function(){
this.number = 0;
};
// method definition
View.prototype.foo = function(){
$('input').on('change', function(){
// former this should be the object instance and
// the latter should be the html element.
this.number = $(this).val();
});
};
View.prototype.foo = function(){
$('input').on('change', function(){
this.number = $(this).val();
}.bind(this)); // bind the callback to the instance of View object
};
View.prototype.foo = function(){
$('input').on('change', function(){
// explicitly set this to be the instance
// while sacrificing generality since code breaks when the object name is not 'view'
view.number = $(this).val();
});
};
var view = new View();
直到$(this).val()之后,$(this)才希望返回输入元素,而不是视图对象
为了以特别的方式解决这个问题,我可以显式地将其设置为一个实例的名称,如下所示
// constructor pattern
var View = function(){
this.number = 0;
};
// method definition
View.prototype.foo = function(){
$('input').on('change', function(){
// former this should be the object instance and
// the latter should be the html element.
this.number = $(this).val();
});
};
View.prototype.foo = function(){
$('input').on('change', function(){
this.number = $(this).val();
}.bind(this)); // bind the callback to the instance of View object
};
View.prototype.foo = function(){
$('input').on('change', function(){
// explicitly set this to be the instance
// while sacrificing generality since code breaks when the object name is not 'view'
view.number = $(this).val();
});
};
var view = new View();
如您所见,这可以解决这一点的模糊性,但也会损害通用性,因为当对象名称不是“视图”时,代码会中断
如上所述,如何使代码在不影响通用性的情况下解决歧义?
请建议一条路。谢谢。许多lib/框架中使用的常见方法如下:
View.prototype.foo = function(){
var self = this; // store this as a local variable
$('input').on('change', function(){
self.number = $(this).val();
});
};