Explain the following JavaScript statement?
This question already has an answer here:
This code is equivalent to:
function Ninja() {
// nothing here
}
var ninja = new Ninja();
Though in the code you listed, the function/object Ninja is not global scope.
The code (function() {...})();
basically says "take whatever function is contained inside here and execute it immediately". So it's creating an anonymous function and calling it right afterwards.
It's called an Immediately-Invoked Function Expression (or IIFE). It creates a new scope and executes the contents immediately. There are many uses for it; the one I use the most is when the this
keyword would change meaning, eg in
var someClass = function() {
this.property = something;
this.update = (function(obj) {
function() {
$('.el').each(function() {
$(this).html( obj.property );
});
};
)(this);
};
While I want to refer to this.property
inside the $('.el').each()
, this
changes meaning within that scope and refers to the current DOM element that is being looped through with .each()
. So by passing this
as a parameter into the IIFE (and calling that parameter obj
) I can use obj.property
to refer to what is this.property
when outside the scope of $('.el').each( ..., function() { ... });
.
Let me know if that makes sense or if you have any questions :)
Why is the function declaration encapsulated in '('s and also why is there a '();' in the end
Its declaring and executing the function at the same time.
You may see: Named function expressions demystified - by Juriy "kangax" Zaytsev
链接地址: http://www.djcxy.com/p/1476.html上一篇: 被JavaScript中的闭包困惑
下一篇: 请解释下面的JavaScript语句?