美文网首页
面试题-你不知道的this指向

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

作者: 小骆驼与秀秀 | 来源:发表于2021-03-24 22:02 被阅读0次

面试题-你不知道的 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

相关文章

网友评论

      本文标题:面试题-你不知道的this指向

      本文链接:https://www.haomeiwen.com/subject/rwrkhltx.html