this指向

1.全局环境下 的this 指向 window



2. 函数的独立调用,函数的内部的this也指向了window

function fn(){

  console.log(this);

}

fn();


3. 当被嵌套的函数独立调用时候,this 默认指向了window
var obj = {

  a:2,

  foo :function (){
    //函数当做对象的方法来调用 this指向了obj
    var that = this;     
function test(){         console.log(this);         
         console.log(that.a)


    }   
  test();
  } }
obj.foo();



4. IIFE 自执行函数
内部this指向window
var a = 10;

function foo(){
  console.log(this);
  (function test(that){
    console.log(that.a);
    console.log(this);

  })(this);
}
var obj = {
  a:2,
  foo:foo
}
obj.foo();



5. 闭包 this 指向 window

var a = 0;

var obj = {
  a:2,

  foo:function(){

    var c = this.a;

    return function test(){

      console.log(this);
      return c;
    }
  }
}
var fn = obj.foo();
console.log(fn());


原文地址:https://www.cnblogs.com/angdh/p/13974428.html