【问题标题】:Reason behind using 'instanceof function() {}'?使用“instanceof function() {}”的原因?
【发布时间】:2011-09-16 14:12:04
【问题描述】:

在Mozilla开发者中心,有一个关于Function.prototype.bind功能的页面,并为不支持该功能的浏览器提供了兼容功能。

但是,在分析此兼容性代码时,我无法找出他们使用instanceof nop 的原因。 nop 已设置为 function() {}。这与bind 上的 ECMA 规范的哪一部分相对应?什么变量是function() {} 的实例?

下面返回false,所以我不完全知道它是干什么用的。进行instanceof function() {} 检查时,哪些情况会返回 true?

(function() {}) instanceof (function() {}) // false

代码如下:

Function.prototype.bind = function( obj ) {
    if(typeof this !== 'function')
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');

    var slice = [].slice,
        args = slice.call(arguments, 1), 
        self = this, 
        nop = function () {}, 
        bound = function () {
          return self.apply( this instanceof nop ? this : ( obj || {} ), 
                              args.concat( slice.call(arguments) ) );    
        };

    bound.prototype = this.prototype;

    return bound;
};

【问题讨论】:

    标签: javascript function bind instanceof prototype-programming


    【解决方案1】:

    有人编辑了使它有用的部分。这是它过去的样子:

    Function.prototype.bind = function( obj ) {
        var slice = [].slice,
        args = slice.call(arguments, 1), 
        self = this, 
        nop = function () {}, 
        bound = function () {
            return self.apply( this instanceof nop ? this : ( obj || {} ), 
                                args.concat( slice.call(arguments) ) );    
        };
    
        // These lines are the important part
        nop.prototype = self.prototype;
        bound.prototype = new nop();
    
        return bound;
    };
    

    我在这里回答了另一个问同样问题的问题(但代码正确时):mozilla's bind function question

    this instanceof nop 检查的原因是,如果您将绑定函数作为构造函数调用(即使用 new 运算符),this 将绑定到新对象,而不是您传递给 @987654326 的任何内容@。

    为了解释“重要部分”,nop 基本上被插入到原型链中,因此当您将函数作为构造函数调用时,this nop 的实例.

    因此,如果您运行 var bound = original.bind(someObject);,原型链将如下所示:

    原版的 | 无 | 边界

    我猜他们为什么使用nop 而不是this instanceof self 是因为绑定函数将拥有它自己的prototype 属性(继承自self's)。它可能不应该是它被部分编辑掉的原因。无论如何,现在的代码是不正确的,但只要您不将该函数用作构造函数,它就可以工作。

    【讨论】:

      【解决方案2】:

      该实现似乎存在错误。 nop 从未用于(实例化任何东西)期望 instanceof 检查,这对任何事情都不会成立,因为无法从 nop 实例化任何对象,nop 被深埋在该闭包中。

      考虑一下:

      // Identical definition, but different Function instances
      var nop = function () {},
          mop = function () {};
      
      var obj1 = new mop;
      
      obj1 instanceof mop // true
      obj1 instanceof nop // false
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-22
        • 1970-01-01
        • 2018-08-08
        • 1970-01-01
        • 1970-01-01
        • 2019-05-27
        相关资源
        最近更新 更多