max
max

Reputation:

jQuery closure & object property access

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.

Upvotes: 1

Views: 1241

Answers (5)

max
max

Reputation:

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();
});

Upvotes: 2

max
max

Reputation:

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();
});

Upvotes: 0

max
max

Reputation:

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);
    }

};

Upvotes: 0

AnthonyWJones
AnthonyWJones

Reputation: 189457

Add a self reference:-

var test = {
   a: 3,
   init: function() {
       var self = this
       $("body").click(function() {
          alert(self.a);
       });
   }
};

Upvotes: 0

PatrikAkerstrand
PatrikAkerstrand

Reputation: 45721

You have to refer to the object:

test.a

Upvotes: 0

Related Questions