4
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;
    };
}

this is pick from bind MDC,i don't understand what is this instanceof fNOP ? this doing. would someone to teach me,please? i want to know why not use oThis || window directly.

island205
  • 1,702
  • 16
  • 27
  • 3
    What exactly do you not understand? What [`instanceof`](https://developer.mozilla.org/en/JavaScript/Reference/Operators/instanceof) is doing? Or the [conditional operator `cond ? true : false`](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Conditional_Operator)? Both are covered in the MDN documentation. If you ask for the *reason* why this construct is used, it is explained [here](http://stackoverflow.com/questions/5774070/mozillas-bind-function-question). – Felix Kling Apr 13 '12 at 10:16
  • possible duplicate of [Question mark in JavaScript](http://stackoverflow.com/questions/1771786/question-mark-in-javascript) – Felix Kling Apr 13 '12 at 10:21
  • i understand both.but i want to know why not use `oThis || window` directly. – island205 Apr 13 '12 at 10:28
  • Well, `this` is different from `oThis` and `window`, so you would change the functionality. It seems you are probably more interested in the question I linked to already: [mozilla's bind function question](http://stackoverflow.com/questions/5774070/mozillas-bind-function-question). – Felix Kling Apr 13 '12 at 10:31

1 Answers1

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

if this is an instance of fNOP, the first argument will be this. if not, then it will be oThis if it's "truthy" (not null, not undefined and anything synonymous to false), or window of oThis is false.

its a shorthand to this code:

if(this instanceof fNOP){
    firstparameter = this;
} else {
    if(oThis){
        firstParameter = oThis;
    } else {
        firstParameter = window;
    }
}
Joseph
  • 107,072
  • 27
  • 170
  • 214