问题
I have an event firing and even though it's inside of the function from which I'm trying to access variables, I get Uncaught TypeError: Cannot read property '...' of undefined
. So, let's say:
( function($) {
$.fn.main = function() {
this.setting = 1;
$("#someElement").scroll( function() {
console.debug(this.setting);
} );
}
} )(jQuery);
I'm sure it has something to do with timing, but then again, I could be wrong. Should I make a copy of this
and make that public? Anyone? Thanks.
回答1:
The value of this
cannot be pinned in a closure as the this
gets its value dynamically.
try :
var self = this;
And reference self.
回答2:
Just copy this
to another variable
( function($) {
$.fn.main = function() {
this.setting = 1;
var that = this;
$("#someElement").scroll( function() {
console.debug(that.setting);
} );
}
} )(jQuery);
回答3:
( function($) {
$.fn.main = function() {
this.setting = 1; // "this" refers to the "$.fn.main" object
$("#someElement").scroll( function() {
console.debug(this.setting); // "this" refers to the "$('#someElement')" object
} );
}
} )(jQuery);
If you want to use the this
from $.fn.main
, you can store the variable. The following would work:
( function($) {
$.fn.main = function() {
var that = this
that.setting = 1; // "this.setting" would also work
$("#someElement").scroll( function() {
console.debug(that.setting); // You need to reference to the other "this"
} );
}
} )(jQuery);
回答4:
the this
inside the scroll method is refereing to the scroll method. The method is bound to be called on the scroll event of element with id 'someElement'. and the scope of the binding object is lost.
来源:https://stackoverflow.com/questions/10120271/accessing-this-type-javascript-variables-from-other-functions