您当前的位置: 首页 > 

暂无认证

  • 1浏览

    0关注

    92582博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Function.prototype.mybind

发布时间:2021-04-12 23:14:12 ,浏览量:1

目录
  • 1、概念
  • 2、MDN链接地址
  • 3、代码
    • 3.1、功能函数
    • 3.2、被调用的函数
    • 3.3、被指向的对象
    • 3.4、函数调用
1、概念

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} 
关注
打赏
1653961664
查看更多评论
立即登录/注册

微信扫码登录

0.6255s