Javascript 访问嵌套函数中的成员变量
我有一个类,它在内部函数中使用jQuery函数。 如何在jQuery回调函数中引用成员变量 请参阅下面的代码:Javascript 访问嵌套函数中的成员变量,javascript,jquery,oop,inheritance,Javascript,Jquery,Oop,Inheritance,我有一个类,它在内部函数中使用jQuery函数。 如何在jQuery回调函数中引用成员变量 请参阅下面的代码: var UriParser = function(uri) { this._uri = uri; // let's say its http://example.com }; UriParser.prototype.testAction = function() { $('a').on('click', function(eve
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
}
}
问题是
此
在事件处理程序中没有引用UriParser
对象,它引用的是被单击的dom元素
一种解决方案是使用闭包变量
UriParser.prototype.testAction = function () {
var self = this;
$('a').on('click', function (event) {
//use self._uri
})
}
另一个是用于传递自定义执行上下文
UriParser.prototype.testAction = function () {
$('a').on('click', $.proxy(function (event) {
//use this._uri
}, this))
}
问题是
此
在事件处理程序中没有引用UriParser
对象,它引用的是被单击的dom元素
一种解决方案是使用闭包变量
UriParser.prototype.testAction = function () {
var self = this;
$('a').on('click', function (event) {
//use self._uri
})
}
另一个是用于传递自定义执行上下文
UriParser.prototype.testAction = function () {
$('a').on('click', $.proxy(function (event) {
//use this._uri
}, this))
}