underScore学习1:匿名函数中call(this)的作用

时间:2021-07-12 01:11:09

匿名函数中(function(){}).call(this) 中的.call(this) 有什么用?

  • 我们都知道,.call()可以改变函数执行时的context,即this的指向,源码中的.call(this)
  • 主要就是,把当前的context传递给匿名函数。
  • So, if for whatever reason you use this, it's a way to make the IIFE act as if it were a member function of Foo,
  • specifically when creating instances of a user-defined object type.
    function Foo(){
(function(){
console.log(this); //Foo
}).call(this); (function(){
console.log(this); //undefined in strict or global
})();
} var bar = new Foo;