views:

403

answers:

5

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.

A: 

You have to refer to the object:

test.a
PatrikAkerstrand
That couples the code to the fact that the overall object is stored in a variable called "test". This not a good pattern since test is external to the object.
AnthonyWJones
A: 

Add a self reference:-

var test = {
   a: 3,
   init: function() {
       var self = this
       $("body").click(function() {
          alert(self.a);
       });
   }
};
AnthonyWJones
This usually works, but will fail if: test.init.call(otherContext)
PatrikAkerstrand
@Machine: true but why would you want to do that? Accessing variables outside of an object may work but doing so leads to some serious spaggeti. Such a pattern should be considered a bad smell and avoided if possible
AnthonyWJones
Ok, this works:<pre>var test = { a: 3, init: function() { var self = this; $("body").click(function() { test.doit(); }); }, doit: function() { var self = this; alert(self.a); }};</pre>but I need to reuse the doit function, so now this doesn't work:<pre>var test = { a: 3, init: function() { var self = this; $("body").click(self.doit); }, doit: function() { var self = this; alert(self.a); }};</pre>as the "this" in doit refers to the $("body") obj. ideas?
max
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);
    }

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

max
It might be an idea for you to read the SOFAQ. Please don't keep adding answers as if SO were a forum or NG. Just refine your existing answer.
AnthonyWJones
+2  A: 

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

max