时常会搞混 bind
、apply
、call
这三者的用法以及来意,现在就一次性讲清楚吧
apply
apply() 方法调用一个具有给定 this 的函数,以及一个数组(或类数组对象)的形式提供的参数。
1 2 3 4 5
| const nums = [1, 2, 3, 4]; const max = Math.max.apply(null, nums); console.log(max); const min = Math.min.apply(null, nums); console.log(min);
|
call
call() 方法与 apply() 方法类似。该方法调用一个具有给定 this 的函数,从第二个参数之后全都是参数。
1 2 3 4 5 6 7 8 9
| 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);
|
bind
bind() 方法创建一个新的函数,在 bind() 被调用时,这个函数的 this 被指定为 bind() 的第一个参数,其余的参数将作为新函数的参数,供调用时被使用。
1 2 3 4 5 6 7 8 9 10 11 12
| const module = { x: 42, getX: function () { return this.x; }, };
console.log(module.getX()); const unboundGetX = module.getX; console.log(unboundGetX()); const boundGetX = unboundGetX.bind(module); console.log(boundGetX()); // 42
|
基础的 bind() 实现:
在不考虑 new 绑定的情况下,这样写是足够了的。
1 2 3 4 5 6
| Function.prototype.myBind = function (obj), ...args) { const self = this; return function (...newArgs) { return self.apply(obj), args.concat(newArgs)); }; };
|
考虑 new 之后就要在原型上面去做一部分修改
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| function fun(...args) { console.log(this); console.log(args); }
func.prototype.cher = function () { console.log(1); }
Function.prototype.myBind = function (obj,...args) {
var _that = this; var newBind = function(...list) { var targetObj = this instanceof newBind ? this : obj; that.apply(targetObj ,[...list,...args]); } newBind.prototype = Object.create(_that.prototype); newBind.prototype.constructor = _that;
return newBind; }
var fn2 = fun.myBind({a:1},4,3); var newFn2 = new fn2(1,2); console.log(newFn2); console.log(newFn2.cher());
|