JS this指向

this 的取值,是在函数真正被调用执行的时候确定的,而不是在函数被定义是确定的,因为 this 的取值是执行上下文的一部分,每次调用函数,都会产生一个新的执行上下文环境。

this 的取值,分四种情况:

  1、构造函数

function Fn() {
    this.name = 'GaoSirs';
    this.year = '9012';
     
    console.log(this);    // Fn {name: "GaoSirs", year: "9012"}
}

var f1 = new Fn();
console.log(f1.name); // GaoSirs

  2、函数作为对象的一个属性

var obj = {
    name:'GaoSirs',
    fn:function(){
        console.log(this); //   {name: "GaoSirs", fn: ƒ}
        console.log(this.name); // GaoSirs
    }  
}

obj.fn();

---------------------------

var obj = {
    name:'GaoSirs',
    fn:function(){
        console.log(this); //   Window
        console.log(this.name); // undefined
    }  
}

var f1 = obj.fn;
f1(); // fn函数被赋值到了另一个变量中,并没有作为obj的一个属性被调用,作为普通函数被调用,this 执行 Window
 

  3、函数用 call 或 apply 调用

  

var obj = {
    year:'9012'
}

var fn = function(){
    console.log(this);   // {year: "9012"}
    console.log(this.year);  // 9012
}

fn.call(obj);  // 把fn函数的 this 指向 obj,实现对obj的继承

  4、全局 & 普通函数调用

  在全局环境下,this 指向 永远是 Window

  普通函数被调用时,this指向也 Window

var year = 9012function fn(){
    console.log(this);  // Window
    console.log(this.year); // 9012
}

fn();

  注意:

var obj = {
    year:'9012',
    fn:function(){
        function f1(){
            console.log(this);  // Window
            console.log(this.year); // undefined
        }
        f1();
    }
}

obj.fn();

函数f1虽然是在obj.fn内部定义的,但是它仍然是一个普通的函数,this仍然指向window。

  5、ES 中箭头函数的 this

  箭头函数的this定义:箭头函数的this是在定义函数时绑定的,不是在执行过程中绑定的。简单的说,函数在定义时,this就继承了定义函数的对象。定义时候绑定,就是this是继承自父执行上下文中的 this

  

var obj = {
    func: function() {
        console.log(this);
    }, 
    
    say:function() {
        setTimeout(() => {
            console.log(this);
        })
    }
}


obj.func();  // obj {func: ƒ, say: ƒ}
obj.say();   // obj {func: ƒ, say: ƒ}

--------------------------------------------
var a=11;
function test2(){
  this.a=22;
  let b=()=>{console.log(this.a)}
  b();
}
var x=new test2();  // 22
 
随笔整理自 
https://www.cnblogs.com/wangfupeng1988/p/3988422.html
https://www.cnblogs.com/var-chu/p/8476464.html
感谢博主分享!
原文地址:https://www.cnblogs.com/gaosirs/p/10569985.html