Lea Cohen
Lea Cohen

Reputation: 8190

Why doesn't the function recognize the member when using "this"

I have a class called imageResizing. It has a member, MAX_WIDTH_ORIGINAL_IMG which is defined as 650:

MAX_WIDTH_ORIGINAL_IMG:650,

and a function called setMaxSizeOriginalImg, and the only thing it does is alert the member MAX_WIDTH_ORIGINAL_IMG:

alert(this.MAX_WIDTH_ORIGINAL_IMG);

I call the function on load as follows:

 addEventSimple(window,'load',imageResizing.setMaxSizeOriginalImg);

And the alert box says undefined.

However, when I change the alert to alert(imageResizing.MAX_WIDTH_ORIGINAL_IMG);, the alert box shows 650.

Here is the whole code of my HTML page:

<html>
<head></head>
    <body>
        <script>
        if (typeof(addEventSimple)=='undefined') {
                                addEventSimple = function(obj,evt,fn) {
                                    if (obj.addEventListener)
                                        obj.addEventListener(evt,fn,false);
                                    else if (obj.attachEvent)
                                        obj.attachEvent('on'+evt,fn);
                                }
                    }   


         var imageResizing={

                MAX_WIDTH_ORIGINAL_IMG:650,

                setMaxSizeOriginalImg:function()
                {
                    alert(imageResizing.MAX_WIDTH_ORIGINAL_IMG);

                }
            };


            addEventSimple(window,'load',imageResizing.setMaxSizeOriginalImg);
    </script>
</body>
</html>

I would like to understand what the difference is between using this and the actual classname, when the function is in the class itself

Upvotes: 2

Views: 73

Answers (1)

Quentin
Quentin

Reputation: 943579

If you call foo.bar() then this is foo.

You are passing the value of foo.bar. This is somewhat akin to:

baz = foo.bar;

So when it gets called, it is a bit like baz().

Pass a new function instead:

addEventSimple(window,'load',function () { imageResizing.setMaxSizeOriginalImg() });

Upvotes: 3

Related Questions