3

I came across this form of self invoking function. What is the "!" for?

!function (a) {
    // something
}(1);

I don't know whether there is an existing question or not. Sorry if this is a dup.

4

3 回答 3

4

By using !, it's evaluating the anonymous function (thereby requiring it to run). Without that, you'd get an error.

And, as others have said, it will invert the result of whatever the function returns, if you're assigning it or evaluating it.

于 2013-01-01T00:33:46.883 回答
0

The not is meaningless unless the functions return value is assigned to something. If assigned, the left hand side will get the not of the result of the self executing function. The result will be the value explicitly returned or the last calculated value in the function.

于 2013-01-01T00:33:39.160 回答
0

if it is returning something, it will just inverse the result:

console.log(!(function(a) { return (a == 1); })(1));

will return false. true if you give 0 or anything else.

于 2013-01-01T00:34:37.470 回答