程序员

理解js中this指向

2020-11-03  本文已影响0人  少_游

先“死记硬背”以下几条规律:
1、在函数体中,非显式或隐式的简单调用函数时,在严格模式下,函数内的this会被绑定到undefined上,非严格模式下,绑定到全局对象 window上
2、一般使用new 调用构造函数时,构造函数内的this会指向新创建的对象上(返回的那个对象)
3、一般通过上下文对象调用函数时,函数体内的this会绑定到该对象上(调用函数的那个对象)
4、在箭头函数中,this的指向是由外层作用域来决定的

一、全局环境中的this

const foo = {
    name: 'shaoyou',
    say: function () {
        console.log(this.name) //undefined
    } 
}
const f1 = foo.say
f1()

say方法借助f1隐式调用,函数体内的this指向全局

二、上线文对象调用中的this

const personal = {
    name: 'a',
    bro: {
        name: 'b',
        do: function () {
            console.log(this.name)  //b
        }
    }
}
personal.bro.do()

当代码中有嵌套关系时,this会指向最后调用它的对象

三、通过bind、apply、call改变this指向

三个函数都可以改变this指向,不同的是:apply(第二个参数是数组)、call会运行函数,bind返回一个新函数,但是不会运行

四、构造函数和this

function Bar () {
    this.user = 'shaoyou'
    return {}
}
const bar = new Bar()
console.log(bar.user)  //undefined
function Foo () {
    this.user = 'shaoyou'
    return 1
}
const result = new Foo()
console.log(result.user)  //shaoyou

如果构造函数中返回一个值,如果这个值是一个对象,那么this就指向返回的这个新对象;如果返回的是一个基本类型,那么this仍指向实例对象

五、箭头函数中的this
function foo () {
    return () => {
        console.log(this.a)
    }
}

const obj1 = {
    a: '1'
}
const obj2 = {
    a: '2'
}
const bar = foo.call(obj1)
console.log(bar.call(obj2)) //1

foo.call改变了foo内部的this指向,将foo中this绑定到了obj1上,所以箭头函数中(bar)的this也绑定到了obj1上;使用bar.call并不能改变this的指向

六、手动实现bind

Function.prototype.bind = Function.prototype.bind || function (context) {
    let me = this;  //此时me指向调用bind的那个函数,即下面的foo
    let args = Array.prototype.slice.call(arguments, 1)
    return function bound () {
        var innerArgs = Array.prototype.slice.call(arguments)
        var finalArgs = args.concat(innerArgs)
        return me.apply(context, finalArgs)
    }
}
function foo (a) {
    this.a = a
}
let obj1 = {}
var bar = foo.bind(obj1)

摘自:《前端开发核心知识进阶》一书

上一篇下一篇

猜你喜欢

热点阅读