Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

Are "(function ( ) { } ) ( )" and "(function ( ) { } ( ) )" functionally equal in JavaScript?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No; they are identical


However, if you add new beforehand and .something afterwards, they will be different.

Code 1

new (function() {
    this.prop = 4;
}) ().prop;

This code creates a new instance of this function's class, then gets the prop property of the new instance.
It returns 4.

It's equivalent to

function MyClass() {
    this.prop = 4;
}
new MyClass().prop;

Code 2

new ( function() {
    return { Class: function() { } }; 
}() ).Class;

This code calls new on the Class property.
Since the parentheses for the function call are inside the outer set of parentheses, they aren't picked up by the new expression, and instead call the function normally, returning its return value.
The new expression parses up to the .Class and instantiates that. (the parentheses after new are optional)

It's equivalent to

var namespace = { Class: function() { } };

function getNamespace() { return namespace; }

new ( getNamespace() ).Class;
//Or,
new namespace.Class;

Without the parentheses around the call to getNamespace(), this would be parsed as (new getNamespace()).Class — it would call instantiate the getNamespace class and return the Class property of the new instance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...