Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

iife - A Javascript function

Please explain the following way of writing a function in javascript functions :

(function (){
 // some code 
})()

I understand the fact that because of the trailing braces " () ", the function will execute immediately but but what does enclosing the function in the braces mean?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

As RobG pointed out, this is the only valid statement choice in your original question.

(function (){
 // some code 
}())

This is executed right after it is parsed, and provides a way to out-scope the code inside the function from the rest of your code. This is called a closure (see Closures on MDN) and may help with memory leaks in your scripts.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...