问答

手动实现bind时为什么要用原型式继承?

作者:admin 2021-04-20 我要评论

这是MDN上关于bind原理的一块代码,原 网页链接 : var ArrayPrototypeSlice = Array.prototype.slice; Function.prototype.bind = function(otherThis) { var b...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

这是MDN上关于bind原理的一块代码,原网页链接

  var ArrayPrototypeSlice = Array.prototype.slice;
  Function.prototype.bind = function(otherThis) {
    var baseArgs= ArrayPrototypeSlice.call(arguments, 1),
        baseArgsLength = baseArgs.length,
        fToBind = this,
        fNOP    = function() {},
        fBound  = function() {
          baseArgs.length = baseArgsLength; // reset to default base arguments
          baseArgs.push.apply(baseArgs, arguments);
          return fToBind.apply(
            // {↓此行标记↓}
            fNOP.prototype.isPrototypeOf(this) ? this : otherThis, baseArgs
          );
        };

    if (this.prototype) {
      // Function.prototype doesn't have a prototype property
      fNOP.prototype = this.prototype;
    }
    fBound.prototype = new fNOP();

    return fBound;
  };

在最后,fBound需要将调用bind的函数的prototype继承为自己的prototype,为什么不直接:

  fBound.prototype = this.prototype;

而是绕了一大圈弄了个新函数:

  var fNOP = function() {},
  if (this.prototype) {
      fNOP.prototype = this.prototype;
  }
  fBound.prototype = new fNOP();

这么做的目的是什么呢?

by the way,在第一段的标记代码中:

  // {此行标记}
  fNOP.prototype.isPrototypeOf(this) ? this : otherThis, baseArgs

为什么使用fNop来做instance检测而不使用fBound,这二者有什么区别吗?

劳驾答疑,不胜感激。

###

第一个是为了解决引用类型问题。(借用构造函数进行继承)
第二个你要用fNop做继承难道拿fBound做检测吗?

###

先来举一个例子:

var obj = { name: "Martin" };
var hello = function(str){
    console.log("Hello " + str + ' to ' + this.name);
};
var objHello = hello.bind(obj); 

objHello('JS')

第一个问题:如果直接赋值?fBoundprototypehello?函数的 prototype 也会被修改。因此,我们需要一个中间变量 fNOP,让它等于一个空函数,通过 fNOP 来维护原型关系,并让 fBound.prototypethis.prototype 不再指向同一个原型函数。

第二个问题:我觉得应该使用 fBound 来检测,具体是将 fNOP.prototype.isPrototypeOf(this) 改成 this instanceof fBound

比如上面的代码最后改成用 new 调用

...
var newObj = new objHello('JS');

this instanceof fBound 中的 this,如果是在 new 关键字调用情况下,会指向 newObj,而 newObj 就是 fBound 的实例,this instanceof fBound 就是 true,我们不再使用 otherThis 作为 hellothis,而是直接使用 newObj 作为 hellothis;而当做普通函数调用的时候,this instanceof fBound 就是 falsehello 中的 this 依然指向 otherThis

以上,希望有所帮助 :)

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • nginx响应速度很慢

    nginx响应速度很慢

  • 点击选中的多选框,会在已选那一栏显示

    点击选中的多选框,会在已选那一栏显示

  • PHP 多态的理解

    PHP 多态的理解

  • 关于C语言中static的问题

    关于C语言中static的问题

腾讯云代理商
海外云服务器