JavaScript中this指向——总结

147 阅读1分钟

学习过JavaScript的同学一定遇到this,this有时指向全局对象,有时又会指向当前对象,有时指向实例。。。,让人琢磨不透。这篇文章,总结一下自己这几天对this的学习

this指向思维导图

image.png

普通函数中的this

普通函数

var b = 1
function a() {
    console.log("this=>", this)
    console.log("b=>", this.b)
}
a()

image.png

对象中的方法

var a = 1
var obj = {
    a: 10,
    b: function () {
        console.log("this=>", this)
        console.log("a=>", this.a)
    }
}
obj.b()

image.png

构造函数中的方法

绑定事件的函数

立即执行函数

定时器函数

箭头函数中的this

普通箭头函数

定义在对象中

定义在对象的方法中

定义在定时器中

call,apply,bind中的this

练习题

看几道题巩固一下,答案请拉到文章最后

练习1

var name = 'fxe一'
var obj = {
    name: 'fxe二',
    fn: function () {
        let name = 'fxe三'
        return function () {
            return this.name
        }
    }
}
console.log(obj.fn()())
var fo = obj.fn()
console.log(fo())

练习2

var name = 'fxe一'
var obj = {
    name: 'fxe二',
    fn: function () {
        return this.name
    }
}
console.log(obj.fn()) 
var fo = obj.fn
console.log(fo())

练习3

练习题答案

fxe一
fxe一
fxe二
fxe一