您当前的位置: 首页 > 

暂无认证

  • 1浏览

    0关注

    92582博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Function.prototype.mycall

发布时间:2021-04-12 22:48:19 ,浏览量:1

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

call()方法使用一个指定的this值和单独给出的一个或多个参数来调用一个函数。

2、MDN链接地址

MDN - call

3、代码 3.1、功能函数
Function.prototype.mycall = function(context = window, ...args) { // 如果this不是函数, // 抛出错误, // 退出程序。 if (typeof this !== "function") { throw new TypeError('not a function'); } else { // 否则把函数重新命名为fun, // 并且挂载到context对象上 // 也就是外面传进来的对象(callData) context.fun = this; } // 调用函数 context = context.fun(args); // 将属性删除 delete context.fun; // 返回函数执行结果 return context; }; 
3.2、被调用的函数
function callFun(args) { let conResult = `${args[0]} ${this.sname},${args[1]}${this.age}${args[2]}。`; console.log(conResult); // my name is 黄庭坚,享年60岁。 return { sname: this.sname, age: this.age }; }; 
3.3、被指向的对象
let callData = { sname: "黄庭坚", age: 60 }; 
3.4、函数调用
let callResult = callFun.mycall(callData, 'my name is', '享年', '岁'); console.log(callResult); // {sname: "黄庭坚", age: 60} 
关注
打赏
1653961664
查看更多评论
立即登录/注册

微信扫码登录

0.4743s