手写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方法
分析:
- 函数调用call方法,所以这个方法写在Function.prototype上面
- 获取调用call方法的函数,指定到传入的context上面(这里给定一个名称为 context.fn)
- 获取传入的参数,作为context.fn的入参
- 调用context.fn并返回运行结果
// 手写call方法Function.prototype.Mycall = function (ctx = window, ...rest) {if (!(this instanceof Function)) {console.error(`${this} is not a function`)return}ctx.fn = thisconst res = ctx.fn(...rest)delete ctx.fnreturn res}
apply方法
apply() 方法调用一个具有给定 this 值的函数,以及以一个数组(或一个类数组对象)的形式提供的参数。
const numbers = [5, 6, 2, 3, 7];const max = Math.max.apply(null, numbers);console.log(max);
// Expected output: 7const min = Math.min.apply(null, numbers);console.log(min);
// Expected output: 2
分析:
- 函数调用apply方法,所以这个方法写在Function.prototype上面
- 获取调用apply方法的函数,指定到传入的context上面(这里给定一个名称为 context.fn)
- 获取传入的参数,这里是一个数组的形式,作为context.fn的入参
- 调用context.fn并返回运行结果
// 手写apply方法Function.prototype.Myapply = function (ctx = window, arrParams = []) {if (!(this instanceof Function)) {console.error(`${this} is not a function`)return}ctx.fn = thisconst res = ctx.fn(...arrParams)delete ctx.fnreturn 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: undefinedconst boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// Expected output: 42
分析:
- 函数调用bind方法,所以这个方法写在Function.prototype上面
- 生成一个新的函数并返回
- 在返回的函数中,通过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 = thisreturn function () {return _this.call(ctx, ...rest)}}