美文网首页
实现call、apply、bind

实现call、apply、bind

作者: frameworkofthin | 来源:发表于2019-04-13 14:54 被阅读0次

使用方法

Call

function say(name1, name2) {
  console.log(this, name1, name2)  
}
let a = { age: 1 }
say.call(a, '张', '三')
// { age: 1 } '张' '三'

Apply

function say(name1, name2) {
  console.log(this, name1, name2)  
}
let a = { age: 1 }
say.apply(a,[ '张', '三'])
// { age: 1 } '张' '三'

Bind

function say(name1, name2) {
  console.log(this, name1, name2)  
}
let a = { age: 1 }
let b = say.bind(a,[ '张', '三'])
console.log(b) // 指向a的say函数
b()
// { age: 1 } '张' '三'

thisArg
  • 当不传、为null、undefine时,this指向window
  • 传递的是函数时,this指向该函数的引用
  • 传递的是原始值(1, '1', false),this指向原始值的自动包装对象
  • 传递的是对象,则指向该对象

三者之间的区别

  • 改变this后,执行函数
    1. call:参数直接在thisArg后面书写
    2. apply:第二个参数为一个数组,该数组的元素会被当成参数传递到函数中去
  • 改变this后,返回了绑定了this的函数
    1. bind

应用

求最大值
let a = [1, 4, -3, 5]
Math.max.apply(null, a)
//解构的方式 Math.max(...a)
伪数组转成数组
let a = {
  0: 'a',
  1: 'b',
  2: 'c',
  length: 3
}
Array.prototype.slice(a) // 注:slice的参数为空时,默认从0开始切割
// ['a', 'b', 'c']
继承

请看原型的章节

如何实现

Call
  1. 如果没有传入thisArg,则默认指向window
  2. 改变this,并执行该函数,同时传入参数
Function.prototype.myCall = function(context) {
  context = context || window
  context.fn = this // this指向的是原函数 a.call(),指向的就是a函数
  // 这里的arguments包括了context,所以需要将其剔除
  let [, fnParmas] = [...arguments]
  let res = context.fn(fnParmas)
  delete context.fn // 这里会有点问题,当传进来的context有fn字段时,会被覆盖,在这里删除。造成了字段的丢失
  return res
}

优化~~~

Function.prototype.myCall = function(context) {
  context = context || window
  const s = Symbol() // Symbol在对象的字段中是唯一存在的
  context[s] = this 
  let [, fnParmas] = [...arguments]
  let res = context[s](fnParmas)
  return res
}
Apply
Function.prototype.myApply = function(content) {
  const s = Symbol()
  context = content || window
  context[s] = this
  const [, arg] = [...arguments]
  const res = context[s](...arg)
  return res
}
Bind

bind()方法会返回一个函数,当这个函数被调用时,bind()的第一个参数作为他运行时的this,之后的一序列的参数在传递实参之前传入作为他的参数。

  • 返回一个函数
  • bind()的参数 + 返回的函数的参数一起传入该函数。(thisArg不作为参数传入)
Function.prototype.myBind = function (context) {
  const _this = this
  const arg1 = Array.prototype.slice(arguments, 1)
  var fBound = function () {
    const arg2 = Array.prototype.slice(arguments)
    // 因为new的时候,this会指向实例,实例 instanceof fBound就为true,然后将绑定的函数的this指向该实例
    return _this.apply(this instanceof fBound ? this : context, arg1.concat(arg2))
  }

  // 修改返回函数的的prototype为绑定函数的prototype,实例就可以继承绑定函数的原型中的值
  fBound.prototype = this.prototype
  return fBound
}

bind参考文章:https://github.com/mqyqingfeng/Blog/issues/12

题目

题目一

执行以下代码会出现什么结果

var altwrite = document.write;
altwrite("hello");

会报错,因为window上没有altwrite方法。主要考点就是this指向的问题,altwrite()函数改变this的指向global或window对象,导致执行时提示非法调用异常。使用call改变this指向即可。

相关文章

网友评论

      本文标题:实现call、apply、bind

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