Search code examples
javascriptjqueryextend

Scoping issue with jQuery Function Extend


I'm experimenting with having an object extended and that object containing multiple functions. I'm having trouble explaining it, so let me just show you my code. Let's start with what is working:

(function ($) {
    $.fn.extend({
        Hello: function() {
            console.log("Well, hello back!");
            console.log($(this));
        }
    });
})(jQuery);

In HTML:

<script>
    $(document).ready(function() {
        $('.target').Hello();
    });
</script>

The console log of $(this) is giving me the callee element "target", as expected.

Now, let's try it this way:

(function ($) {
    $.fn.extend({
        Response: {
            Hello: function() {
                console.log("Well, hello back!");
                console.log($(this));
            }
        }
    });
})(jQuery);

In HTML:

<script>
    $(document).ready(function() {
        $('.target').Response.Hello();
    });
</script>

This is still spitting out "Well, hello back!" in the console, but I'm no longer getting the callee when I use $(this). I'm instead getting the Hello function.

How do I get the callee? I've tried this.parent, which does not work. Please help!


Solution

  • As others have pointed out, you can't really do what you are asking for, but you can do something that looks almost the same.

    By capturing 'this' with a closure, you can access it further down in your object structure:

    $.fn.extend({
        Response: function () {
            var self = this;
            return {
                Hello: function () {
                    console.log(self);
                }
            };
        }
    });
    
    $('.target').Response().Hello();