Javascript: using the 'this' function in object literature giving an error

I need to fix the megamenu system for the site on which I was transferred, and I encountered an error.

Once the DOM is ready (jQuery enabled), the megamenu rendering function is executed. In this case, to change the size, a listener is added to retransmit this function, re-render the code. However, I get javascript errors that believe that this rendering function when called from an object is actually a window function, so I get "Uncaught TypeError: Object [object DOMWindow] does not have a" render "method .

But the function still works!

here is a brief snapshot of the code:

var jkmegamenu=
{
 ...
    render:function($)
    {
    ...
        $(window).bind("resize", function()
        {
          this.render($);
        }

    }

}

jkmegamenu.render($) ( , , - jQuery, ), self: this, . , , jQuery (, http://www.phpied.com/3-ways-to-define-a-javascript-class/), , - ?

kent.ac.uk, , , .

+3
3

this JavaScript , , ++, # Java. , , . : this

, , this jkmegamenu, jQuery proxy , , "" ( this):

var jkmegamenu=
{
 ...
    render:function($)
    {
    ...
        $(window).bind("resize", $.proxy(function()
        {
          this.render($);
        }, this));
    }

}

:

var jkmegamenu=
{
 ...
    render:function($)
    {
    ...
        var inst = this; // Remember `this`
        $(window).bind("resize", function()
        {
          // Use it
          inst.render($);
        });
    }

}

... , this DOM, (, window, ).

- . :

, jkmegamenu , , , this :

var jkmegamenu = (function() {
    var inst = {};

    // ...

    inst.render = jkmegamenu_render;
    function jkmegamenu_render($)
    {
        $(window).bind("resize", function()
        {
          inst.render($);
          // Or just jkmegamenu_render($);
        });
    }

    // Could have some private functions here, just by
    // virtue of not adding them to `inst`

    // ...

    return inst;
})();

, , , .

factory ( "", , JavaScript ) .

+5

Javascript , , , 'this' , . , 'this' , . :

var jkmegamenu=
{
 ...
    render:function($)
    {
    ...
        var that = this;
        $(window).bind("resize", function()
        {
          that.render($);
        }
    }
}
+3

this DOM.

this , , this . .

For more information on Javascript, thissee this article: http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/

+1
source

All Articles