最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

A Better inline javascript function? - Stack Overflow

programmeradmin0浏览0评论

Is there a better way to write this code? i tried function(){}(); but i got an error so i had to use DUMMY as a placeholder var. The function should run before alert b does. Whats a better way of writing this?

var DUMMY = function(){
    var names = "i dont want to be seen";
    alert('A');
}; DUMMY();

alert('B');

Is there a better way to write this code? i tried function(){}(); but i got an error so i had to use DUMMY as a placeholder var. The function should run before alert b does. Whats a better way of writing this?

var DUMMY = function(){
    var names = "i dont want to be seen";
    alert('A');
}; DUMMY();

alert('B');
Share Improve this question asked Jun 17, 2010 at 13:56 user34537user34537 1
  • @Amnon: Nothing. I put it to make it more clear for certain people who may notice both alerts and understand i desire the function to be ran before that line. – user34537 Commented Jun 18, 2010 at 3:31
Add a ment  | 

3 Answers 3

Reset to default 4

I actually use the syntax you say doesn't work all the time. The thing is, you need to either store the return value, or make it an expression. So either:

var foo = function() { return false; }();

or

(function() { return false; }());

Note the difference between Pointy's answer on this one. The expression is the entire function (including the calling ()), not just the function declaration. Either way will do the same thing. Use what you feel is more readable (Personally I like this syntax better, but to each their own)...

You can use parentheses to make it look like an expression:

(function() { alert("hi"); })();

I recently saw this (at the TXJS conference):

!function() { alert("hi"); }();

The leading "!" serves the same purpose: the parser sees an expression instead of a function definition statement.

For now the best is

(()=>{})()

or even

!()=>{}
发布评论

评论列表(0)

  1. 暂无评论