开发者

Calling the function immediately on the call of the page

开发者_开发知识库var ObjectLiteral = {
    myName:function() {
    }
}
  1. I want to call the myName function immeditetly when the page is loaded.
  2. I am not sure hot to write a self calling function inside an ObjectLiteral...


You can't assign a function while simultaneously calling it (since calling it means that its return value gets assigned instead). You have to do this in two steps.

var ObjectLiteral = {
    myName:function() {
    }
};
ObjectLiteral.myName();


Just because no one mentioned it:

var ObjectLiteral = {
    myName: function() {
        console.log('myName was called!');
        return arguments.callee;
    }()
}

Since arguments.callee is deprecated in ES5, we would need to give the method a name:

var ObjectLiteral = {
    myName: function _myName() {
        console.log('myName was called!');
        return _myName;
    }()
}

Done. The method would get called at pageload and would still be callable later on. The caveat of doing it that way is the this context value which is replaced with window or undefined (strict) on the self-executing method. But you could apply some magic to solve that aswell. For instance, invoking .call(ObjectLiteral) in es3 or .bind(ObjectLiteral) in es5.

var ObjectLiteral = {
    myName: function _myName() {
        console.log('myName was called!');
        return _myName;
    }.call(ObjectLiteral)
}

Looks like I was wrong (damn!). The idea ok, but the assignment to ObjectLiteral is not done on the first invocation of myName. Therefore, the above code will only run from the second call on, which of course makes it useless anyway. You would need to invoke another context, but that would be just overkill.

It still does work after all, but it screws up if you need to access this, otherwise its a fine solution I think.


For your first question:

The simplest possible answer is to add this line to your script:

window.onload = ObjectLiteral.myName();

A better answer is to include that line somewhere in a larger function assigned to window.onload:

window.onload = function () {
    ....
    ObjectLiteral.myName();
}

An even better answer is to scope things properly in case window has been reassigned.

For the second question, what to you mean by self-calling? (EDIT: n/m, Quentin answered)


Taking into account you want to execute your code after page load, jQuery is very suitable for that:

$(function() {
  // called then page loaded..
  var ObjectLiteral = {
    myName:function() {
    }
  };

  ObjectLiteral.myName();

});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜