美文网首页
基础-bind方法及实现原理

基础-bind方法及实现原理

作者: 冰冰啦 | 来源:发表于2019-03-16 16:28 被阅读0次

1. bind方法

  • 函数调用bind方法, 可以指定函数内部的this, 并把bind函数的第一个参数之后的参数拼接到返回的新函数的实参之前.
  • 示例
var obj = {a: 1}
function fn(a,b,c,d,e,f) {
  console.log(this)
  console.log(a,b,c,d,e,f)
}
var newFn = fn.bind(obj,1,2,3)
newFn(4,5,6) 
  • 输出
[object Object] {
  a: 1
}
1
2
3
4
5
6

2. 实现一个自己的bind方法

Function.prototype._bind = function(obj) {
  if(typeof this !== 'function') {
    throw new Error("只有函数才能调用bind方法")
  }
  let that = this
  // 去掉arguments的第一项 
  let args = Array.prototype.slice.call(arguments,1)
  return function() {
    // 去掉arguments第一项
    arguments = [].splice.call(arguments,1)
    args = args.concat(arguments)
    that.apply(obj,args)
  }
}

相关文章

网友评论

      本文标题:基础-bind方法及实现原理

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