手动实现bindcallapply方法

12次阅读

共计 2169 个字符,预计需要花费 6 分钟才能阅读完成。

转载请注明出处

bind()

bind()方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被 bind 的第一个参数指定,其余的参数将作为新函数的参数供调用时使用。

语法:

function.bind(thisArg[,arg1[,arg2[, …]]])

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

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

var boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42
以下是对 bind() 的一个实现:
Function.prototype.bind = function(context) {if (typeof this !== 'function') {throw new TypeError('Error')
  }
  let _this = this
  let args = [...arguments].slice(1)
  return function F() {
    // 判断是否被当做构造函数使用
    if (this instanceof F) {return _this.apply(this, args.concat([...arguments]))
    }
    return _this.apply(context, args.concat([...arguments]))
  }
}

apply()

apply() 方法调用一个具有给定 this 值的函数,以及作为一个数组(或类似数组对象)提供的参数。

语法:

func.apply(thisArg, [argsArray])

示例:
var numbers = [5, 6, 2, 3, 7];

var max = Math.max.apply(null, numbers);

console.log(max);
// expected output: 7

var min = Math.min.apply(null, numbers);

console.log(min);
// expected output: 2
以下是对apply() 的一个实现:
Function.prototype.apply = function(context) {
  // context 就是 apply 的第一个参数,在这里也就是 obj
  // 判断是否是 undefined 和 null
  if (typeof context === 'undefined' || context === null) {context = window}
  // this 也就是调用 apply 的函数 把函数赋值给 context 下面的一个键,这里是 fn
  context.fn = this
  // arguments 就是传进来的参数
  let args = arguments[1]
  let result
  if (args) {result = context.fn(...args)
  } else {result = context.fn()
  }
  delete context.fn
  return result
}
let test = function (sex) {console.log(this.name + sex)
}
let obj = {name: '我是'}
test.apply(obj, ['test'])

call()

call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。

语法:

fun.call(thisArg, arg1, arg2, …)

示例:
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"
以下是对 call() 的一个实现:
Function.prototype.call = function(context) {
  // context 就是 call 的第一个参数,在这里也就是 obj
  // 判断是否是 undefined 和 null
  if (typeof context === 'undefined' || context === null) {context = window}
  // this 也就是调用 call 的函数 把函数赋值给 context 下面的一个键,这里是 fn
  context.fn = this
  // arguments 就是传进来的参数
  let args = [...arguments].slice(1)
  let result = context.fn(...args)
  delete context.fn
  return result
}
let test = function (sex) {console.log(this.name + sex)
}
let obj = {name: '我是'}
test.call(obj, 'test')

参考资料


  • bind()
  • call()
  • apply()

欢迎浏览我的个人网站

正文完
 0