本文共 723 字,大约阅读时间需要 2 分钟。
要实现bind函数需要以下几个关键点:
1. 通过保存this实现上下文绑定
2. 确保参数传递功能原封不动
3. 调用目标函数时,正确设置this值
Function.prototype.mybind=function(context]{ if(typeof this!=='function'){ throw new Error("this not a function"); } var arr=Array.from(arguments).slice(1); var mybound=function(){ arr=arr.concat(...arguments); return this.apply(context,arr); }; return mybound; });
定义一个对象:
var obj={ name:'lijia' };
定义一个函数:
function foo(age,pp){ console.log(this.name,age,pp); }
绑定函数并执行:
foo.mybind(obj,20,30)()
输出结果应为:
['lijia',20,30]
转载地址:http://cfizk.baihongyu.com/