手写JavaScript中的call、bind、apply方法

手写JavaScript中的call、bind、apply方法

call方法

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

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方法

分析:

  1. 函数调用call方法,所以这个方法写在Function.prototype上面
  2. 获取调用call方法的函数,指定到传入的context上面(这里给定一个名称为 context.fn)
  3. 获取传入的参数,作为context.fn的入参
  4. 调用context.fn并返回运行结果
  // 手写call方法
    Function.prototype.Mycall = function (ctx = window, ...rest) {
        if (!(this instanceof Function)) {
            console.error(`${this} is not a function`)
            return
        }
        ctx.fn = this
        const res = ctx.fn(...rest)
        delete ctx.fn
        return res
    }

apply方法

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

const numbers = [5, 6, 2, 3, 7];

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

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

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

console.log(min);
// Expected output: 2

分析:

  1. 函数调用apply方法,所以这个方法写在Function.prototype上面
  2. 获取调用apply方法的函数,指定到传入的context上面(这里给定一个名称为 context.fn)
  3. 获取传入的参数,这里是一个数组的形式,作为context.fn的入参
  4. 调用context.fn并返回运行结果
  // 手写apply方法
    Function.prototype.Myapply = function (ctx = window, arrParams = []) {
        if (!(this instanceof Function)) {
            console.error(`${this} is not a function`)
            return
        }
        ctx.fn = this
        const res = ctx.fn(...arrParams)
        delete ctx.fn
        return res
    }

bind方法

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

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

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

const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// Expected output: 42

分析:

  1. 函数调用bind方法,所以这个方法写在Function.prototype上面
  2. 生成一个新的函数并返回
  3. 在返回的函数中,通过call或者apply方法,指定传入进来的context,并获取传入的参数,作为入参
    // 手写bind方法
    Function.prototype.Mybind = function (ctx = window, ...rest) {
        if (!(this instanceof Function)) {
            console.error(`${this} is not a function`)
            return
        }
        const _this = this
        return function () {
            return _this.call(ctx, ...rest)
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值