es5 bind和es3函数模拟的bind的区别

本文深入探讨了ES5中bind函数的内部实现机制,解释了其如何通过原型链优化性能,以及如何正确使用bind来创建可绑定this的函数副本。文章详细分析了bind函数的工作原理,并提供了实例演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在讨论这个问题之前,我们先看一下在es5出现内置的bind函数之前,是怎么模拟bind的

Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      // closest thing possible to the ECMAScript 5 internal IsCallable function
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var aArgs = Array.prototype.slice.call(arguments, 1), 
        fToBind = this, 
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(this instanceof fNOP && oThis
                                 ? this
                                 : oThis || window,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
实际上一个绑定函数没有prototype属性, Thus, a bound function does not have a prototype property or the [[Code]] (the function body code),[[FormalParameters]] (the list of formal parameter names), and [[Scope]] (a parent lexical or variable environment) internal properties.

如果返回绑定函数的prototype属性,则会输出目标函数的prototype

这么做的好处是优化性能,绑定函数本身并不是一个完整的函数,而是原函数的中间代理。

绑定函数的[[Call]][[Construct]] and [[HasInstance]]都被重载,实际指向原函数





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值