面试题-你不知道的 this 指向

面试和业务中常见的问题是 this 的指向问题。作为一等公民的函数,this 的指向经常让人捉摸不透。我们可以按照以下逻辑来进行 this 的指向理解

  1. 箭头函数:this 指向定义的时候所属的对象自身

  2. 普通函数:this 指向函数的调用者

const module = {
  x: 42,
  getX: function() {
    return this.x;
  }
};

const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined

unboundGetX是定义的一个全局变量,当unboundGetX被调用时,调用者是window。window并没有x属性,所以会打印undefined

改变this指向的办法

箭头函数

无法直接改变,因为实际上箭头函数没有自己的this,实际上this的取值是取自于外层代码块对应的this,且看下面es6转成es5的demo

es6
function foo() {
	setTimeout(() => {
    	console.log(this.id)
    })
}
es5
function foo() {
  var _this = this;

  setTimeout(function () {
    console.log(_this.id);
  });
}

可以看出,箭头函数内部对应的this会换成外部的_this

普通函数

call
Function.prototype.call

参数:

function.call(thisArg, arg1, arg2, ...)
  • thisArg: 要使用的this值
  • arg1, arg2, 依次传入的函数的参数

demo

function Product(name, price) {
  this.name = name;
  this.price = price;
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

console.log(new Food('cheese', 5).name);
// expected output: "cheese"
apply
Function.prototype.apply

参数:

function.call(thisArg, [arg1, arg2, ...])
  • thisArg: 要使用的this值
  • [arg1, arg2,…] 与call不同,传入的是传入的函数的参数数组
bind

bind用来创建一个新函数,当这个新函数被调用时,传入bind的第一个参数则作为新函数的this

Function.prototype.bind

参数(同call)

function.bind(thisArg, arg1, arg2, ...)

通过bind改变this指向的demo

const module = {
  x: 42,
  getX: function() {
    return this.x;
  }
};

const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined

const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值