一网打尽 this,对执行上下文说 Yes


在这里插入图片描述

✍创作者:全栈弄潮儿
🏡 个人主页: 全栈弄潮儿的个人主页
🏙️ 个人社区,欢迎你的加入:全栈弄潮儿的个人社区
📙 专栏地址,欢迎订阅:前端架构师之路

this 到底指向谁?

全局环境下的this、箭头函数的 this、构造函数的 this、this 的显隐性和优先级,等等,真实环境多样。

一句话总结:

谁调用它,this 就指向谁。

也就是说,this 的指向是在调用时确定的。这么说没有太大的问题,可是并不全面。

事实上,调用函数会创建新的属于函数自身的执行上下文。执行上下文的调用创建阶段会决定 this 的指向。到此,我们可以得出的一个结论:

this 的指向,是在调用函数时根据执行上下文所动态确定的。

  • 在函数体中,简单调用该函数时(非显式/隐式绑定下),严格模式下 this 绑定到 undefined,否则绑定到全局对象 window/global;
  • 一般构造函数 new 调用,绑定到新创建的对象上;
  • 一般由 call/apply/bind 方法显式调用,绑定到指定参数的对象上;
  • 一般由上下文对象调用,绑定在该对象上;
  • 箭头函数中,根据外层上下文绑定的 this 决定 this 指向。

全局环境下的 this

这种情况相对简单直接,函数在浏览器全局环境中被简单调用,非严格模式下 this 指向 window;在 use strict 指明严格模式的情况下就是 undefined。我们来看例题,请描述打印结果:

function f1 () {
    console.log(this)
}
function f2 () {
    'use strict'
    console.log(this)
}
f1() // window
f2() // undefined

上一题比较基础,再看一道例子:

const foo = {
    bar: 10,
    fn: function() {
       console.log(this)
       console.log(this.bar)
    }
}
var fn1 = foo.fn
fn1()

这里 this 仍然指向的是 window。虽然 fn 函数在 foo 对象中作为方法被引用,但是在赋值给 fn1 之后,fn1 的执行仍然是在 window 的全局环境中。因此输出 window 和 undefined,它们相当于:

console.log(window)
console.log(window.bar)

还是上面这道例题,如果调用改变为:

const foo = {
    bar: 10,
    fn: function() {
       console.log(this)
       console.log(this.bar)
    }
}
foo.fn()

将会输出:
{bar: 10, fn: ƒ}
10
因为这个时候 this 指向的是最后调用它的对象,在 foo.fn() 语句中 this 指向 foo 对象。请记住:在执行函数时,如果函数中的 this 是被上一级的对象所调用,那么 this 指向的就是上一级的对象;否则指向全局环境。

上下文对象调用中的 this

如上结论,面对下题时我们便不再困惑:

const student = {
    name: 'Lucas',
    fn: function() {
        return this
    }
}
console.log(student.fn() === student)

最终结果将会返回 true。
当存在更复杂的调用关系时:

const person = {
    name: 'Lucas',
    brother: {
        name: 'Mike',
        fn: function() {
            return this.name
        }
    }
}
console.log(person.brother.fn())

在这种嵌套的关系中,this 指向 最后 调用它的对象,因此输出将会是:Mike。再看一道更高阶的题目:

const o1 = {
    text: 'o1',
    fn: function() {
        return this.text
    }
}
const o2 = {
    text: 'o2',
    fn: function() {
        return o1.fn()
    }
}
const o3 = {
    text: 'o3',
    fn: function() {
        var fn = o1.fn
        return fn()
    }
}

console.log(o1.fn())
console.log(o2.fn())
console.log(o3.fn())

答案是:o1、o1、undefined,你答对了吗?
我们来一一分析。
第一个 console 最简单,o1 没有问题。难点在第二个和第三个上面,关键还是看调用 this 的那个函数。
第二个 console 的 o2.fn(),最终还是调用 o1.fn(),因此答案仍然是 o1。
最后一个,在进行 var fn = o1.fn 赋值之后,是“裸奔”调用,因此这里的 this 指向 window,答案当然是 undefined。

如果我们需要让:
console.log(o2.fn())
输出 o2,该怎么做?

一般可能会想到使用 bind/call/apply 来对 this 的指向进行干预,这确实是一种思路。如果不能使用bind/call/apply,有别的方法吗?

const o1 = {
    text: 'o1',
    fn: function() {
        return this.text
    }
}
const o2 = {
    text: 'o2',
    fn: o1.fn
}

console.log(o2.fn())

还是应用那个重要的结论:this 指向 最后 调用它的对象,在 fn 执行时,挂到 o2 对象上即可,我们提前进行了赋值操作。

bind/call/apply 改变 this 指向

bind/call/apply,他们都是用来改变相关函数 this 指向的,但是 call/apply 是直接进行相关函数调用;bind 不会执行相关函数,而是返回一个新的函数,这个新的函数已经自动绑定了新的 this 指向,开发者需要手动调用即可。

const target = {}
fn.call(target, ‘arg1’, ‘arg2’)
相当于:
const target = {}
fn.apply(target, [‘arg1’, ‘arg2’])
相当于:
const target = {}
fn.bind(target, ‘arg1’, ‘arg2’)()

我们来看一道例题:

const foo = {
    name: 'lucas',
    logName: function() {
        console.log(this.name)
    }
}
const bar = {
    name: 'mike'
}
console.log(foo.logName.call(bar))

将会输出 mike。

构造函数和 this

function Foo() {
    this.bar = "Lucas"
}
const instance = new Foo()
console.log(instance.bar)

答案将会输出 Lucas。

new 操作符调用构造函数,具体做了什么?

  • 创建一个新的对象;
  • 将构造函数的 this 指向这个新对象;
  • 为这个对象添加属性、方法等;
  • 最终返回新对象。

以上过程,也可以用代码表述:

var obj  = {}
obj.__proto__ = Foo.prototype
Foo.call(obj)

如果在构造函数中出现了显式 return 的情况,那么需要注意分为两种场景:

function Foo(){
    this.user = "Lucas"
    const o = {}
    return o
}
const instance = new Foo()
console.log(instance.user)

将会输出 undefined,此时 instance 是返回的空对象 o。

function Foo(){
    this.user = "Lucas"
    return 1
}
const instance = new Foo()
console.log(instance.user)

将会输出 Lucas,也就是说此时 instance 是返回的目标对象实例 this。

结论: 如果构造函数中显式返回一个值,且返回的是一个对象,那么 this 就指向这个返回的对象;如果返回的不是一个对象,那么 this 仍然指向实例。

箭头函数中的 this 指向

箭头函数使用 this 不适用以上标准规则,而是根据外层(函数或者全局)上下文来决定。

const foo = {  
    fn: function () {  
        setTimeout(function() {  
            console.log(this)
        })
    }  
}  
console.log(foo.fn())

这道题中,this 出现在 setTimeout() 中的匿名函数里,因此 this 指向 window 对象。如果需要 this 指向 foo 这个 object 对象,可以巧用箭头函数解决:

const foo = {  
    fn: function () {  
        setTimeout(() => {  
            console.log(this)
        })
    }  
} 
console.log(foo.fn())

// {fn: ƒ}

单纯箭头函数中的 this 非常简单, 但是综合所有情况,结合this 的优先级考察,这时候 this 指向并不好确定。

this 优先级相关

我们常常把通过 call、apply、bind、new 对 this 绑定的情况称为显式绑定;根据调用关系确定的 this 指向称为隐式绑定。

那么显式绑定和隐式绑定谁的优先级更高呢?

function foo (a) {
    console.log(this.a)
}

const obj1 = {
    a: 1,
    foo: foo
}

const obj2 = {
    a: 2,
    foo: foo
}

obj1.foo.call(obj2)
obj2.foo.call(obj1)

输出分别为 2、1,也就是说 call、apply 的显式绑定一般来说优先级更高

function foo (a) {
    this.a = a
}

const obj1 = {}

var bar = foo.bind(obj1)
bar(2)
console.log(obj1.a)

上述代码通过 bind,将 bar 函数中的 this 绑定为 obj1 对象。执行 bar(2) 后,obj1.a 值为 2。即经过 bar(2) 执行后,obj1 对象为:{a: 2}。

当再使用 bar 作为构造函数时:

var baz = new bar(3)
console.log(baz.a)

将会输出 3。bar 函数本身是通过 bind 方法构造的函数,其内部已经对将 this 绑定为 obj1,它再作为构造函数,通过 new 调用时,返回的实例已经与 obj1 解绑。 也就是说:
new 绑定修改了 bind 绑定中的 this,因此 new 绑定的优先级比显式 bind 绑定更高。

我们再看:

function foo() {
    return a => {
        console.log(this.a)
    };
}

const obj1 = {
    a: 2
}

const obj2 = {
    a: 3
}

const bar = foo.call(obj1)
console.log(bar.call(obj2))

将会输出 2。由于 foo() 的 this 绑定到 obj1,bar(引用箭头函数)的 this 也会绑定到 obj1,箭头函数的绑定无法被修改。

如果将 foo 完全写成箭头函数的形式:

var a = 123
const foo = () => a => {
    console.log(this.a)
}

const obj1 = {
    a: 2
}

const obj2 = {
    a: 3
}

var bar = foo.call(obj1)
console.log(bar.call(obj2))

将会输出 123。

如果仅仅将上述代码的第一处变量 a 的赋值改为:

const a = 123
const foo = () => a => {
    console.log(this.a)
}

const obj1 = {
    a: 2
}

const obj2 = {
    a: 3
}

var bar = foo.call(obj1)
console.log(bar.call(obj2))

答案将会输出为 undefined,原因是因为使用 const 声明的变量不会挂载到 window 全局对象当中。因此 this 指向 window 时,自然也找不到 a 变量了。

实现一个bind 函数

Function.prototype.bind = Function.prototype.bind || function (context) {
    var me = this;
    var 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);
    }
}

这样的实现基本满足需求。但是, 如果 bind 返回的函数如果作为构造函数,搭配 new 关键字出现的话,我们的绑定 this 就需要“被忽略”。

为了实现这样的规则,就应该需要考虑如何区分这两种调用方式。 具体来讲bound 函数中就要进行 this instanceof 的判断。

Function.prototype.bind = Function.prototype.bind || function (context) {
    var me = this;
    var args = Array.prototype.slice.call(arguments, 1);

    // 返回一个新的函数
    var bound = function() {
        var innerArgs = Array.prototype.slice.call(arguments);
        var finalArgs = args.concat(innerArgs);
        return me.apply(this instanceof bound ? this : context, finalArgs);
    };

    // 设置原始函数的原型为新函数的原型
    bound.prototype = Object.create(me.prototype);

    return bound;
};

另外一个细节是,函数具有 length 属性,表示形参的个数。上述实现方式形参的个数显然会失真。我们的实现就需要对 length 属性进行还原。

Function.prototype.bind = Function.prototype.bind || function (context) {
    var me = this;
    var args = Array.prototype.slice.call(arguments, 1);

    // 返回一个新的函数
    var bound = function() {
        var innerArgs = Array.prototype.slice.call(arguments);
        var finalArgs = args.concat(innerArgs);
        return me.apply(this instanceof bound ? this : context, finalArgs);
    };

    // 设置原始函数的原型为新函数的原型
    bound.prototype = Object.create(me.prototype);

    // 还原 length 属性
    bound.length = Math.max(me.length - args.length, 0);

    return bound;
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

全栈弄潮儿²⁰²⁴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值