Javascript: rounded parentheses surrounding comma separated expressions
playing on js console i faced a curious syntax, i wonder if someone can
tell me more on that.. try this:
>( function f(){console.log('i am f')} , (function x(){console.log('i am
x')})() , y=2 , console.log('hello') )
i am x
hello
undefined
>f()
ReferenceError: f is not defined
>this.y
2
this will fail:
( var c=2 ) SyntaxError: Unexpected token var
so comma separated expressions inside parentheses are evaluated,
assignments happens to be against global scope, but named function
declarations references stay trapped inside just like a closure more...
putting that line inside a function declaration called with new:
function C(){
( function f(){console.log('i am f')} , (function x(){console.log('i
am x')})() , y=2 , console.log('hello') )
}
and then instantiating:
>var c=new C()
i am x
hello
undefined
>c.y
undefined
>this.y
2
happens exactly the same, just as executed in the global scope!
whats the usage / purpose of this construct?
one more:
>( function f(){console.log('i am f')} , f() )
ReferenceError: f is not defined
so the named function can't be referenced neither inside brackets
No comments:
Post a Comment