js new call apply bind的底层实现

new

1. 以 Object.protoype 为原型创建一个新对象

2. 以新对象为 this,执行函数的 [[call]]

3. 如果 [[call]] 的返回值是对象,那么,返回这个对象,否则返回第一步创建的新对象

1
2
3
4
5
function myNew(fn, ...args) {
  const obj = Object.create(fn.prototype);
  const ret = fn.call(obj, ...args);
  return ret instanceof Object ? ret : obj;
}

 

call

实际上就是把方法挂在对象上,执行然后删除

1
2
3
4
5
6
7
8
9
10
Function.prototype.myCall = function(context, ...args) {
    if (typeof this !== 'function') {
        throw new TypeError('this is not a function')
    }
    context = context || window;
    context.fn = this;
    const ret = context.fn(...args);
    delete context.fn;
    return ret
}

例子:fn.call(null,10,20,30);

 

apply

原理和call一样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Function.prototype.myApply = function (context, arg) {
    if (typeof this !== 'function') {
        throw new TypeError('this is not a function')
    }
    context = context || window;
    context.fn = this;
    let ret;
    if (arg) {
        ret = context.fn(...args);
    } else {
        ret = context.fn();
    }
    delete context.fn;
    return ret
}

 例子:fn.apply(null,[10,20,30]); 

 

bind

bind原理就是封一层闭包

1
2
3
4
5
6
7
8
9
10
function.prototype.myBind = function (context, ...bindArgs) {
    if (typeof this !== 'function') {
        throw new TypeError('this is not a function');
    }
    const _this = this;
    return function Fn(...execArgs) {
        const args = bindArgs.concat(execArgs);
        return _this.call(this instanceof Fn ? this : context, ...args);
    }
}

例子:fn.bind(opp,10,20)

 

可以形象的描述为:超人有飞的能力,我借用下超人会飞的能力,我也会飞了。

posted @   Peter_Yang0942  阅读(88)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2020-07-22 小程序弹出层覆盖不了canvas
点击右上角即可分享
微信分享提示