自己实现一个call、apply、bind方法
1、call的实现
思路,js中this是根据上下文来决定的,如果是一个方法,this指向这个方法被调用的对象
//如何自己实现一个call Function.prototype.myCall = function() { //obj即相当于上面的k var [obj, ...args] = arguments; console.log({arguments}) //this相当于上面的a obj['fn'] = this; //获取call第二个开始的参数 //相当于k.a, 即将a的this指向k obj['fn'](...args); delete obj['fn']; } function a(n){ console.log(this.m, n); } var k = { m: 2 } a.myCall(k, 1);
或
Function.prototype.myCall = function() { let [context, ...args] = arguments let funNane = Symbol('fn') context[funNane] = this context[funNane](...args) delete context[funNane] }
2、实现一个apply
//如何自己实现一个apply Function.prototype.myApply = function() { //obj即相当于上面的k var [obj, args] = arguments; console.log({arguments}) //this相当于上面的a obj['fn'] = this; //获取call第二个开始的参数 //相当于k.a, 即将a的this指向k obj['fn'](...args); delete obj['fn']; } function a(n, p){ console.log(this.m, n, p); } var k = { m: 2 } a.myApply(k, [1, 3]);
或
Function.prototype.myApply = function() { let [context, args] = arguments let funNane = Symbol('fn') context[funNane] = this context[funNane](...args) delete context[funNane] }
3、实现一个bind
Function.prototype.myBind = function(object) { let obj = object || window; obj.fn = this; let arg = [...arguments].slice(1); return function() { obj.fn.apply(object, arg); } }
或
Function.prototype.myBind = function() { console.log(arguments) let [context, ...args] = arguments let funNane = Symbol('fn') context[funNane] = this return () => context[funNane](...args) }