开发者

setTimeout inside of anonymous function

I want to call editObject() ins开发者_JAVA技巧ide of my jQuery function, the initalisation call does work, but setTimeout doesn't work, how to get it running? Console says that editObject is not defined when called by setTimeout:

(function($){
    $.fn.extend({

                    ...

                    editObject()

            function editObject() {
                alert("Test!");
                setTimeout('editObject()', 1000);
            }

            return this.each(function() {
                var o = options;
            });
        }
    });
})(jQuery);

Thanks for help!


It doesn't work because editObject() is declared in the scope of your anonymous function, but setTimeout() evals the string you passed it in a global context. Try this:

setTimeout(editObject, 1000);


You could try this:

setTimeout(function(){ editObject.call() }, 1000);

Or:

setTimeout(arguments.callee, 1000);


You should avoid using the string version of setTimeout.

I believe that, in this case, Javascript is looking for the function window.editObject and this does not exist.

You should use:

setTimeout(editObject,1000);

instead, as this is grabbing a reference to the object at call-time and so the function will be available to Javascript, for calling, when the timeout expires


Use the function reference directly (rather than a string, which is evaluated in a global context), like this:

setTimeout(editObject, 1000);


UPDATE: I certainly misunderstood the problem, my original code edited to be working:

var foo = function () {
    var that = this;
    that.editObject = function() {
      alert('Test');
      setTimeout(that.editObject, 1000);
    }
}
new foo().editObject();

...

Whenever the Javascript engine will try to call "editObject()" defined in your jQuery function, it is out of your jQuery function's scope, it is actually in the global scope, but your editObject() function is defined in your jQuery function.

You can create the editObject in the global scope or create a reference to your jQuery function and pass it in your setTimeout call, like:

var that = this;
that.editObject = function() {
  alert('Test');
  setTimeout(that.editObject(), 1000);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜