如何理解js中this指向:由执行上下文决定/在执行时确定?

对于this指向的解释,在MDN(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)中有这么一句话,

In most cases, the value of this is determined by how a function is called (runtime binding).

大概意思是说,this的值是由这个函数如何被调用来决定的。

我把它理解为:
函数定义的时候,this的指向是不确定的(函数体的代码主要是一些通用逻辑 - universal logic)
只有在真正调用的时候,才能确定this的指向(函数体的逻辑才被赋予了具体的含义 - specific meaning)


通过两个情形来理解

(注:以下的讨论都基于严格模式及普通函数。
全局环境中,在严格模式下, this指向undefined, 在非严格模式下,this指向window)

1. 一个函数在全局环境定义的

  • 如果在全局环境中调用,this指向undefined
  • 如果通过一个对象调用, this指向该对象
// 一个函数在全局环境定义的
function getValue () {
    console.log('this 指向', this);
    this && console.log('this.value:', this.value);
}
class A {
    constructor (value) {
        this.value = value;
    }

    getValueForA = getValue;
}

// 运行查看结果
console.log('***如果在全局环境中调用,this指向undefined***');
getValue();

console.log('***如果通过一个对象调用,this指向该对象***');
const a = new A('a');
a.getValueForA(); // a

以上代码的输出结果为:
在这里插入图片描述

2. 一个函数在类中定义的

  • 如果在全局环境中调用,this指向undefined
  • 如果通过一个对象调用,this指向该对象
// 一个函数在全局环境定义的
class A {
    constructor (value) {
        this.value = value;
    }

    getValueForA () {
        console.log('this 指向', this);
        this && console.log('this.value:', this.value);
    };
}

// 运行查看结果
console.log('***如果通过一个对象调用,this指向该对象***');
const a = new A('a');
a.getValueForA(); // a

console.log('***如果在全局环境中调用,this指向undefined***');
const getValue1 = A.prototype.getValueForA;
const getValue2 = a.getValueForA;
getValue1();
getValue2();

以上代码的输出结果为:
在这里插入图片描述


结论

函数定义就是定义,this的指向是不确定的,只有在真正调用的时候,才能确定this的指向。

即使是在类中定义的方法,它的this指向并不是确定指向该方法所在的对象,也是要等调用的时候才知道。

如果你理解了,你应该知道下面的这段代码,输出应该是什么了:

class A {
    constructor (value) {
        this.value = value;
    }

    getValueForA () {
        console.log('this 指向', this);
        this && console.log('this.value:', this.value);
    };
}
class B {
    constructor (value) {
        this.value = value;
    }
}

// 运行查看结果
const a = new A('a');
const b = new B('b');
b.getValueForB = a.getValueForA;
b.getValueForB();

输出结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值