如何手写call, apply, bind~

call

Function.prototype.call(this, arg1, arg2, …..) 能够改变this,而且传入参数,马上执行,返回函数返回值javascript

手写calljava

Function.prototype.myCall = function(context = window, ...args) {
  context = context || window; // 参数默认值并不会排除null,因此从新赋值
  context.fn = this; // this是调用call的函数
  const result = context.fn(...args);
  delete context.fn; // 执行后删除新增属性
  return result;
}
复制代码

apply

Function.prototype.apply(this, [arg1, arg2, …..]) 能够改变this,而且传入参数,与call不一样的是,传入的参数是数组或类数组,马上执行,返回函数返回值数组

手写apply:app

Function.prototype.myApply = function(context = window, args = []) {
  context = context || window; // 参数默认值并不会排除null,因此从新赋值
  context.fn = this; // this是调用call的函数
  const result = context.fn(...args);
  delete context.fn;
  return result;
}
复制代码

bind

Function.prototype.bind(this, arg1, arg2, …) 能够绑定this,而且传入参数,方式与call相同,可是不会执行,返回已绑定this的新函数函数

手写bind:ui

Function.prototype.myBind = function(context, ...args) {
  const _this = this;
  return function Bind(...newArgs) {
    // 考虑是否此函数被继承
    if (this instanceof Bind) {
      return _this.myApply(this, [...args, ...newArgs])
    }
    return _this.myApply(context, [...args, ...newArgs])
  }
}
复制代码
相关文章
相关标签/搜索