热点面试题:聊聊对 this 的理解?

聊聊对 this 对象的理解?

定义

  • 在执行上下文中的一个属性,它指向最后一次调用这个属性或方法的对象。通常有四种情况来判断。

四种情况如下

1. 函数调用模式:当一个函数不是一个对象的属性时,直接作为函数来调用时, 严格模式下指向 undefined, 非严格模式下,this 指向全局对象。

// 严格模式
"use strict";
var name = "window";
var doSth = function () {
    console.log(typeof this === "undefined");
    console.log(this.name);
};
doSth(); // true,// 报错,因为this是undefined

// 非严格模式
let name2 = "window2";
let doSth2 = function () {
    console.log(this === window);
    console.log(this.name2);
};
doSth2(); // true, undefined

2. 方法调用模式:如果一个函数作为一个对象的方法来调用时,this 指向当前这个对象

var name = "window";
var doSth = function () {
    console.log(this.name);
};
var student = {
    name: "lc",
    doSth: doSth,
    other: {
        name: "other",
        doSth: doSth,
    },
};
student.doSth(); // 'lc'
student.other.doSth(); // 'other'
// 用call类比则为:
student.doSth.call(student);
// 用call类比则为:
student.other.doSth.call(student.other);

3. 构造器调用模式:如果一个函数通过 new 调用时,函数执行前会新创建一个对象,this 指向这个新创建的对象。

var Obj = function (p) {
    this.p = p;
};

var o = new Obj("Hello World!");
o.p; // "Hello World!"

4. apply, call, bind 模式:显式更改 this 指向,严格模式下,指向绑定的第一个参数,非严格模式下,nullundefined 指向全局对象(浏览器中是 window),其余指向被 new Object() 包裹的对象。

  • aplly: apply(this 绑定的对象,参数数组) func.apply(thisValue, [arg1, arg2, ...])
function f(x, y) {
    console.log(x + y);
}

f.call(null, 1, 1); // 2
f.apply(null, [1, 1]); // 2
  • call: call(this 绑定的对象,一个个参数) func.call(thisValue, arg1, arg2, ...)
var doSth = function (name) {
    console.log(this);
    console.log(name);
};
doSth.call(2, "lc"); // Number{2}, 'lc'
var doSth2 = function (name) {
    "use strict";
    console.log(this);
    console.log(name);
};
doSth2.call(2, "lc"); // 2, 'lc'
  • bind: bind(this 绑定的对象) func.bind(thisValue)
var counter = {
    count: 0,
    inc: function () {
        this.count++;
    },
};

var obj = {
    count: 100,
};
var func = counter.inc.bind(obj);
func();
obj.count; // 101

// eg2:
var add = function (x, y) {
    return x * this.m + y * this.n;
};

var obj = {
    m: 2,
    n: 2,
};

var newAdd = add.bind(obj, 5);
newAdd(5); // 20

箭头函数规则

  • 不会使用以上原则,而是根据当前作用域来决定 this, 也就是说箭头函数会继承外层函数,调用的 this 绑定,没有外层函数,则是指向全局(浏览器中是 window)。

this 优先级

  • 构造器模式 > apply, call, bind > 方法调用模式 > 函数调用模式

文章特殊字符描述:

  1. 问题标注 Q:(question)
  2. 答案标注 R:(result)
  3. 注意事项标准:A:(attention matters)
  4. 详情描述标注:D:(detail info)
  5. 总结标注:S:(summary)
  6. 分析标注:Ana:(analysis)
  7. 提示标注:T:(tips)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Immerse_001

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

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

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

打赏作者

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

抵扣说明:

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

余额充值