Immediately self-emitting function and "this"

I want to create a javascript library, so I thought that making it an instantly self-executing function would be nice to do to ensure the security of the area and that’s it.

But now I have a problem using the keyword "this", which I do not quite understand.

How can I make code like this work correctly? He is currently telling me that the "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 property image?

+5
source share
3 answers

I think you have a few problems here:

  • parts init, this.
  • each image , . image this , this , . ( this.num.)

var this = this; init , this.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);
    });
};
+2

, this.image, lib, , each. this, :

this.init = function() {
    var self = this;
    $(parts).each(function() {
        //do something with self.image
        self.image;
    });
};
+1

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

0
source

All Articles