开发者

How do I set a javascript variable to the return of an inline function?

开发者 https://www.devze.com 2022-12-16 16:25 出处:网络
I\'m using the code: var x = function() {return true;}; trying to set x to true, the return value of the function, but instead x is defined as the function itself. How can I set x as the return val

I'm using the code:

var x = function() {return true;};

trying to set x to true, the return value of the function, but instead x is defined as the function itself. How can I set x as the return value of the function? I could easily code around this problem by using a non-inli开发者_StackOverflow中文版ne function or some such, but it bugs me because I'm sure there must be a simple solution.

Thanks.


The solution is to define the function and then invoke it (by adding the extra parentheses at the end):

    var x = ( function() {return true;} ) ();


You're not executing the function, you're setting x to actually be the function.

If you had some variable y, it could take on the value of the function with something like:

var x = function(){ return true; };
var y = x();  // y is now set to true.

or alternatively execute the function in place with:

var x = (function(){ return true; })();


Your code just defines the function and assigns it to x, the function doesn't get called. To call it, put the function in parenthesis and add () after it, like for a normal function call:

    var x = 
        (
            function () { 
                return true;
            } 
        )();
0

精彩评论

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