目录
1、概念
- 1、概念
- 2、MDN链接地址
- 3、代码
-
- 3.1、功能函数
- 3.2、被调用的函数
- 3.3、被指向的对象
- 3.4、函数调用
bind()方法创建一个新的函数,在bind()被调用时,这个新函数的this被指定为bind()的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
2、MDN链接地址MDN - bind
3、代码 3.1、功能函数Function.prototype.mybind = function(context) { // 如果this不是函数, // 抛出错误, // 退出程序。 if (typeof this !== "function") { throw new TypeError('not a function'); } // 获取除了第一个参数外的后面所有参数 let args = [...arguments].slice(1); // 给this函数重新赋值 let fun = this; return function Fn() { // 根据调用方式, // 传入不同绑定值 return fun.apply(this instanceof Function ? this : context, args); }; };3.2、被调用的函数
function bindFun(...args) { let conResult = `${args[0]} ${this.sname},${args[1]}${this.age}${args[2]}。`; console.log(conResult); // my name is 岳飞,享年39岁。 return { sname: this.sname, age: this.age }; };3.3、被指向的对象
let bindData = { sname: "岳飞", age: 39, };3.4、函数调用
let bindResult = bindFun.mybind(bindData, 'my name is', '享年', '岁'); console.log(bindResult); // 返回Fn()函数 console.log(bindResult()); // {sname: "岳飞", age: 39}