[英]Acces member variables in nested functions
我有一个在其内部函数中使用jQuery函数的类。 如何在jQuery回调函数中引用成员变量?
请参阅以下代码:
var UriParser = function(uri) {
this._uri = uri; // let's say its http://example.com
};
UriParser.prototype.testAction = function() {
$('a').on('click', function(event) {
// I need the above this._uri here,
// i.e. http://example.com
}
}
问题是this
里面的事件处理程序没有引用UriParser
对象,它引用了被点击的dom元素。
一种解决方案是使用闭包变量
UriParser.prototype.testAction = function () {
var self = this;
$('a').on('click', function (event) {
//use self._uri
})
}
另一种方法是使用$ .proxy()来传递自定义执行上下文
UriParser.prototype.testAction = function () {
$('a').on('click', $.proxy(function (event) {
//use this._uri
}, this))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.