Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6344187
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T20:35:15+00:00 2026-05-24T20:35:15+00:00

Consider the following jQuery implementation defined using an object literal… $(function() { var myObject

  • 0

Consider the following jQuery implementation defined using an object literal…

$(function() {

    var myObject = {

        methodOne: function()
        {

            $('#element').animate(
                {'marginLeft': '50px'},
                'slow',
                function() {
                    myObject.methodTwo();
                }
            );

        },

        methodTwo: function()
        {

            $('#element').animate(
                {'marginLeft': '-50px'},
                'slow',
                function() {
                    myObject.methodOne();
                }
            );

        }

    } // End myObject

    myObject.methodOne(); // Execute

});

For the record, the above code works just as expected. What I don’t understand is why a subtle and seemingly harmless change like the following…

    methodOne: function()
    {

        $('#element').animate(
            {'marginLeft': '50px'},
            'slow',
            myObject.methodTwo() // No more anonymous function
        );

    },

… to both methodOne and methodTwo causes a browser error stating too much recursion. What’s the difference between how I’ve declared my callback? Also, if I bring back the anonymous function declaration, but modify the object reference to look like this…

    methodOne: function()
    {

        $('#element').animate(
            {'marginLeft': '50px'},
            'slow',
            function() {
                this.methodTwo(); // assuming 'this' refers to 'myObject'
            }
        );

    },

… I get one good pass through methodOne and upon callback my browser freaks out because it cannot find methodTwo. My guess is that I fell out of scope somewhere, but I can’t rightly decide where. Your insight is much appreciated!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T20:35:15+00:00Added an answer on May 24, 2026 at 8:35 pm

    Lets break this down

            $('#element').animate(
                {'marginLeft': '50px'},
                'slow',
                function() {
                    myObject.methodTwo();
                }
            );
    

    In this example you pass a function object as a callback. That function object is called when animation is done. It has the myObject object shared via closure, so it can easily find it and call a method on it. Awesome!

        $('#element').animate(
            {'marginLeft': '50px'},
            'slow',
            myObject.methodTwo() // No more anonymous function
        );
    

    Here something different is going on. As the callback here you are actually passing the return value of myObject.methodTwo(), and not the actual function object. So since methodTwo() doesn’t return anything, then undefined is actually passed as your callback. Meaning that the animate() function thinks there is no callback.

    So maybe you meant to try this!

        $('#element').animate(
            {'marginLeft': '50px'},
            'slow',
            myObject.methodTwo // No more anonymous function or invocation
        );
    

    Well this still wouldn’t work. Now you are passing a function object for the callback, yes, but it will lose context (this). It turns out that when you invoke a function object on it’s own, then this is the global object. Check this out:

    var obj = {
      foo: function() { console.log(this) }
    };
    
    obj.foo() // logs obj
    
    var func = obj.foo;
    func() // logs window (the global object in a browser)
    

    So you cant pass a function object directly in for a callback that is supposed to be invoked like a method with an object as the receiver. Internally to the animate() method there, it executes callback() for you, which is a call that does not preserve the value of this for you at all.

    So why didnt this one work?

        $('#element').animate(
            {'marginLeft': '50px'},
            'slow',
            function() {
                this.methodTwo(); // assuming 'this' refers to 'myObject'
            }
        );
    

    When an anonymous function is invoke as the callback, just like breaking off a method, this defaults to the window object. So this code actually calls window.methodTwo(), which doesn’t exist, and it explodes.

    So the accepted standard JS way to do this your first way.

    someFunc(arg1, arg2, function() {
      someObj.someMethod()
    });
    

    That should always work, even though it seems wasted because you invoking 2 function to do one thing. But as you are discovering it’s the least error prone.

    Learning how this works in JS is a painful experience, but when you get it, you find that the rules are pretty straight forward and easy to manipulate.


    If you still dont like that, you can do some tricky js magic. Like underscore.js bind() method.

    someFunc(arg1, arg2, _.bind(someObj.someMethod, someObj));
    

    This returns a function that will always run with someObj as this which can safely be used as a callback.

    Or if you want to try out CoffeeScript it has a fat arrow to preserve context, wich compiles to JS similar to what the underscore.js bind() method does.

    someObj =
      foo: ->
        someFunc arg1, arg2, =>
          this.bar()
    
      bar: ->
        alert 'got the callback!'
    
    someObj.foo()
    

    In this case, the => style of function declaration preserves the context of the scope where it appears, so this can be safely used.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am having problems using multiple queues in jQuery. Consider the following example: $('#example').click(function()
Consider the following function using jQuery: function getVal() { jQuery.get('/relative/url/', function (data) { return
Consider the following markup: <x> <y>code1</y> <z>stuff</z> <y>code2</y> <z>foobar</z> </x> Using jQuery, how do
Consider the following Jquery code: var previewImage = $('#prev'); var newLink = $('<a/>').attr('href', name);
Consider the following code: (function($) { function hello(who) { console.log('Hello: '+who); } })(jQuery); $(document).ready(function()
Please consider the following class. I'm beginning to use JQuery. function AutoHide(elemControl, elemContent) {
Consider the following html snippet <!DOCTYPE html> <html> <head> <script type=text/javascript src=http://code.jquery.com/jquery-1.4.2.js ></script> <script
Consider the following snippet of code: function parseXml(xml) { xmlObject= xml; alert(xmlObject.xml); } function
Consider the following code: var sentences = [ 'Lorem ipsum dolor sit amet, consectetur
Consider following piece of code: declare @var bit = 0 select * from tableA

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.