これらのパターンを何と呼びますか?それらの違いは何ですか?それぞれをいつ使用しますか?他に似たようなパターンはありますか?
(function() {
console.log(this); // window
})();
(function x() {
console.log(this); // window
})();
var y = (function() {
console.log(this); // window
})();
var z = function() {
console.log(this); // window
}();
編集:最後の2つのケースで関数に名前を付けることで、これを行うための2つの一見冗長な方法を見つけました...
var a = (function foo() {
console.log(this); // window
})();
var b = function bar() {
console.log(this);
}();
EDIT2 : これは@GraceShaoによって提供される別のパターンで、関数スコープの外で関数にアクセスできるようにします。
(x = function () {
console.log(this); // window
console.log(x); // function x() {}
})();
console.log(x); // function x() {}
// I played with this as well
// by naming the inside function
// and got the following:
(foo = function bar() {
console.log(this); // window
console.log(foo); // function bar() {}
console.log(bar); // function bar() {}
})();
console.log(foo); // function bar() {}
console.log(bar); // undefined