Java教程

如何理解javascript里的this变量

本文主要是介绍如何理解javascript里的this变量,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

this变量有三个上下文:全局上下文,函数上下文,类上下文。
下面只描述函数上下文的this值。
在大多数情况下,一个函数内的this的值是由这个函数是被如何调用的上下文决定的,而不是由这个函数被如何被定义的上下文决定。不过,箭头函数里的this值由这个箭头函数定义处的上下文决定。

mdn web docs是这样描述函数上下文的this值:

Inside a function, the value of this depends on how the function is called.
In most cases, the value of this is determined by how a function is called (runtime binding). ES5 introduced the bind() method to set the value of a function's this regardless of how it's called, and ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context).


1. 普通函数里的this
普通函数的this值由这个函数被调用处的上下文决定,而不是这个函数被定义处的上下文决定。
示例代码

function test() { // test()函数被定义的位置(处)
    console.log({'this': this})
    return this
}
test()  // test()函数被调用的位置(处)
// test()是一个非箭头函数,
// test()里的this值由test()被调用处的上下文决定,
// 而test()被调用处的上下文是全局上下文,
// 所以,test()里的this值是全局上下文的this值。

2. 构造函数里的this

示例代码

function Person(name, age, sex, career) {
    console.log({'this': this}) // 打印this值
    this.name = name
    this.age = age
    this.sex = sex
    this.career = career
    this.getInfo = function() {
        return `${this.name},${this.age}岁,${this.sex},是一个${this.career}`
    }
}
var personA = new Person('孤舟蓑笠翁', 25, '男', '诗人')
// 使用new Person()创建对象时,构造函数Person()被调用了
// Person()是一个非箭头函数
// Person()里的this值是由被调用处的上下文决定的
// 而Person()被调用处的上下文是new Person('孤舟蓑笠翁', 25, '男', '诗人')
// 所以,Person()里的this值就是new Person('孤舟蓑笠翁', 25, '男', '诗人')

 

3. 对象成员方法里的this

示例代码1(箭头函数里的this)

var personA = {
    name: '孤舟蓑笠翁',
    age: 25,
    sex: '男',
    career: '诗人',
    getInfo: () => {
        console.log({'this': this}) // 打印this值
        return `${this.name},${this.age}岁,${this.sex},是一个${this.career}`
    }
}
personA.getInfo()
// getInfo()是一个箭头函数
// getInfo()里的this是由被定义处的上下文决定的
// 而getInfo()被定义处的上下文是personA的上下文
// 而personA上下文的this就是全局对象里的this
// 所以,getInfo()里的this值就是全局对象里的this

示例代码2(非箭头函数里的this)

var personA = {
    name: '孤舟蓑笠翁',
    age: 25,
    sex: '男',
    career: '诗人',
    getInfo: function() {
        console.log({'this': this})
        return `${this.name},${this.age}岁,${this.sex},是一个${this.career}`
    }
}
personA.getInfo()
// getInfo()是一个非箭头函数
// getInfo()里的this是由被调用处的上下文决定的
// 而getInfo()被调用处的上下文是personA
// 所以,getInfo()里的this值是PersonA


4. 箭头函数的this
箭头函数里的this值由这个函数定义(创建)处的上下文决定,而不是这个函数被调用处的上下文决定。


示例代码1(箭头函数里的this)

let personA = {
    name: "机械工程师",
    skillList: ['扫地机器人', '无人机', '洗碗机器人'],
    createRobot: function() {
        return () => {
            console.log({'this': this}) // 打印this值
            let idx = Math.floor(Math.random() * 3)
            return `我是一个${this.skillList[idx]},是被一个${this.name}制造出来的,正在执行自动化任务。`
        }
    }
}
let robot = personA.createRobot()
robot()
// robot()是一个箭头函数,
// robot()里的this值是由robot()定义处的上下文决定的,
// 而robot()定义处的上下文就是createRobot(),
// 而createRobot()里的this值是由createRobot()被调用处的上下文决定,而createRobot()被调用处的上下文是personA,
// 所以robot()里的this值是personA。


示例代码2(非箭头函数里的this)

let personA = {
    name: "机械工程师",
    skillList: ['扫地机器人', '无人机', '洗碗机器人'],
    createRobot: function() {
        return function() {
            console.log({'this': this}) // 打印this值
            let idx = Math.floor(Math.random() * 3)
            return `我是一个${this.skillList[idx]},是被一个${this.name}制造出来的,正在执行自动化任务。`
        }
    }
}
let robot = personA.createRobot()
robot() 
// robot()是一个非箭头函数,
// robot()里的this值是由robot()被调用处的上下文决定的,
// 而robot()被调用处的上下文是全局上下文,
// 所以,robot()里的this值是全局上下文的this值。


 

 

5. 通过Function.prototype.call()或Function.prototype.apply()指定被调用函数里的this值

示例代码

var personA = {
    name: '孤舟蓑笠翁',
    age: 25,
    sex: '男',
    career: '诗人',
    getInfo: function() {
        console.log({'personA_this': this}) // 打印this值
        return `${this.name},${this.age}岁,${this.sex},是一个${this.career}`
    }
}
var personB = {
    name: '独孤求败',
    age: 65,
    sex: '男',
    career: '剑客',
    getInfo: function() {
        console.log({'personB_this': this}) // 打印this值
        return `${this.name},${this.age}岁,${this.sex},是一个${this.career}`
    }
}
personA.getInfo.call(personB) // 将getInfo()函数里的this值绑定到personB。

6. 最后,如果实在不确定一个函数内的this值到底是谁,那么就直接把console.log({'this': this})放在一个函数里,把this值打印出来。


参考文档:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

这篇关于如何理解javascript里的this变量的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!