LoginSignup
57
53

More than 5 years have passed since last update.

即時関数をcall(this)で呼ぶことについて

Last updated at Posted at 2014-06-20

即時関数あれこれ

JavaScriptの即時関数はいろんな書き方が出来る

// よく見かける即時関数
(function () {
  // ...
})();

// underscore.jsの即時関数
(function () {
  // ...
}).call(this);

underscore.jsの即時関数

underscore.jsは何故callで関数を呼び出しているのかというと
JavaScripstのstrictモードでは関数内のthisundefinedになる

e.g.
'use strict';

// よく見かける即時関数
(function () {
  console.log(this); // undefined
})();

// underscore.jsの即時関数
(function () {
  console.log(this); // 即時関数の外のthisが表示される
}).call(this);

strictモードでない場合はどちらの記述でも関数内のthisは実行時のthisが引き渡されるので
strictモードとそうでない場合の振る舞いの違いを吸収するため
call(this)で無名関数を呼んでいるのだと思われる

蛇足

grunt-contrib-coffeeなどでCoffeeScriptから変換されるJavaScriptも(function () {}).call(this);にラップされている
たぶん同じ理由なんだと思う

57
53
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
57
53