2012-04-13 87 views
2
if (!Function.prototype.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 ? this : oThis || window, aArgs.concat(Array.prototype.slice.call(arguments))); 
      }; 

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

     return fBound; 
    }; 
} 

这是从bind MDC中挑选的,我不明白this instanceof fNOP ? this在做什么。有人会教我吗?我想知道为什么不直接使用oThis || window什么是“这个fNOP这个实例?

+3

究竟你还不明白吗?什么['instanceof'](https://developer.mozilla.org/en/JavaScript/Reference/Operators/instanceof)在做什么?或者[条件运算符'cond? true:false'](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Conditional_Operator)?这两个都包含在MDN文档中。如果你要求*理由*为什么使用这个结构,这是解释[这里](http://stackoverflow.com/questions/5774070/mozillas-bind-function-question)。 – 2012-04-13 10:16:18

+0

可能重复的[JavaScript中的问号](http://stackoverflow.com/questions/1771786/question-mark-in-javascript) – 2012-04-13 10:21:38

+0

我明白both.but但我想知道为什么不使用'oThis ||窗口'直接。 – island205 2012-04-13 10:28:21

回答

1
return fToBind.apply(this instanceof fNOP ? this : oThis || window, aArgs.concat(Array.prototype.slice.call(arguments))); 

如果thisfNOP一个实例,第一参数将是this。如果不是,那么它将是oThis,如果它是“truthy”(非空,未定义和任何同义为false),或windowoThis为假。

它的简写这段代码:

if(this instanceof fNOP){ 
    firstparameter = this; 
} else { 
    if(oThis){ 
     firstParameter = oThis; 
    } else { 
     firstParameter = window; 
    } 
}