Hi, Can anyone tell me how to get access to variable "a" here:
var test = { a: 3, init: function() { $("body").click(function() { alert(a); }); } }; test.init();
This doesn't work either: alert(this.a);
Thanks in advance.
Hi, Can anyone tell me how to get access to variable "a" here:
var test = { a: 3, init: function() { $("body").click(function() { alert(a); }); } }; test.init();
This doesn't work either: alert(this.a);
Thanks in advance.
Add a self reference:-
var test = {
a: 3,
init: function() {
var self = this
$("body").click(function() {
alert(self.a);
});
}
};
Ok, this works:
var test = { a: 3, init: function() { var self = this; $("body").click(function() { self.doit(); }); }, doit: function() { var self = this; alert(self.a); } };
but I need to reuse the doit function, so now this doesn't work:
var test = { a: 3, init: function() { var self = this; $("body").click(self.doit); }, doit: function() { var self = this; alert(self.a); } };
Ok, this fixes the second problem:
function test() { var self; return { init: function() { self = this; $("body").click(this.doit); }, doit: function(data, b) { alert(self.testing()); }, testing: function() { return 4; } } } $(function() { var x = test(); x.init(); });
Actually, I prefer this: It's self setting and initializing:
function createX() { var self = { init: function() { $("body").click(this.doit); }, doit: function(data, b) { alert(self.testing()); }, testing: function() { return 4; } } self.init(); return self; } $(function() { createX(); });