改变this指向的三种方式

题记:为什么我们要使用改变this指向?

        我们思考一下,我们往往获取值的方式有下边几种情况,比如自己声明,另外就是通过原型链去找对吗,但是如果你又没有声明,原型链上有没有,那么怎么办呢?就偷,改变this其实就是把其他家的钥匙拿到,取别人的东西。

call()

function.call(thisArg, 参数1, 参数2, 参数3…)
function: 要改变this指向的原函数
thisArg: 要改变到的this指向的目标对象

function fn(animal) {
  this.animal = animal
  console.log('this', this)
  this.b()
}

const obj = {
  animal:'tiger',
  b: function() {
    console.log(`${this.animal} is a man-eating animal`)
  }
}

fn.call(obj,'laohu')

 改变this指向的三种方式_第1张图片

apply()

function.apply(thisArg, [参数1, 参数2, 参数3…])
function: 要改变this指向的原函数
thisArg: 要改变到的this指向的目标对象

function fn(animal) {
  this.animal = animal
  console.log('this', this)
  this.b()
}

const obj = {
  animal:'tiger',
  b: function() {
    console.log(`${this.animal} is a man-eating animal`)
  }
}

fn.apply(obj,['laohu'])

改变this指向的三种方式_第2张图片 

bind()

funtion.bind(thisArg, 参数1, 参数2, 参数3…)
function: 要改变this指向的原函数
thisArg: 要改变到的this指向的目标对象
该方法并不会调用函数,仅仅改变了this指向

 

function fn(animal) {
  this.animal = animal
  console.log('this', this)
  this.b()
}

const obj = {
  animal:'tiger',
  b: function() {
    console.log(`${this.animal} is a man-eating animal`)
  }
}

let fnn = fn.bind(obj,'laohu')
fnn()

改变this指向的三种方式_第3张图片

总结:我们可以看到三个方法都得到了相应的结果,但是我们需要思考两件事,为什么要弄三个?另外就是三个代码书写都什么不同吗?

不同之处:

参数不同:1、apply()的参数是数组形式,可调用 ;2、bind()返回的是一个函数,需要再次调用才行。

我们再想一想,bind()的使用场景就是我们有的时候需要更换this,但是又不想调用,这个不就好了吗?

另外我们常常继承用call,apply经常和数组有关系,比如想用Math里边的函数等等!!!

寄语:

临近新年,希望各位大佬家庭和睦,家人健康,工作顺利。

你可能感兴趣的:(前端面试真实题库,javascript,前端,vue.js)