5

I want to create a javascript library, so I thought making it an immediately self executing function would be a nice thing to do to ensure scope safety and everything.

But now I'm running into a problem with using the "this" keyword that I don't quite understand.

How can I make a code like this work correctly? Currently, it tells me that "image" is undefined.

(function() {

    function lib() {
        this.image = document.getElementById("image");
        this.parts = [
            {name: "part1", num: "1"}
        ];

        this.init = function() {
            $(parts).each(function() {
                var partNum = this.num;
                image.getElementById(partNum).addEventListener("click", function() {
                    toggleHighlight(partNum);
                }, true);
            });
        };
    }

    window.lib = new lib();
})();

window.lib.init();

How can I access the image property?

F.P
  • 15,760
  • 32
  • 114
  • 184
  • Have you tried debugging in a tool like FireBug or Opera DragonFly? Most of the times you can see what the current scope is and what variables are defined. – Marc May 26 '11 at 13:07

3 Answers3

2

I think you have a few issues here:

  • you are referencing parts in your init function without accessing it as a property of this.
  • within the each block, you are accessing image as a global variable but it is not declared globally. You can't access image from this in that block because in that context, this is actually set to the item you are iterating on. (That is why you can access this.num.)

I sugggest you include var that = this; before your init function and use it when accessing properties like that.image.

var that = this;
this.init = function() {
    $(this.parts).each(function() {
        var partNum = this.num;
        that.image.getElementById(partNum).addEventListener("click", function() {
            toggleHighlight(partNum);
        }, true);
    });
};
Mario
  • 2,179
  • 2
  • 18
  • 21
1

If I understand you right you want to get access to this.image property defined inside of lib function from the anonymous function which you provide to the each. To do this you need to preserve this to make it available in the anonymous function:

this.init = function() {
    var self = this;
    $(parts).each(function() {
        //do something with self.image
        self.image;
    });
};
bjornd
  • 20,786
  • 4
  • 51
  • 70
0

You should also capitalize the first letter of function name lib since you are expecting it to be used as a constructor with the new keyword. Take a look at what the author of Javascript The Good Parts has to say about constructor naming conventions in JavaScript.

Mario
  • 2,179
  • 2
  • 18
  • 21