0

I'm using Ruby at daily basis, but Javascript is nowadays everywhere, and I need to learn this language too.

I began with "Learning JavaScript Design Patterns", now I read the 6th edition of "JavaScript: The Definitive Guide".

I'm reading some blogs too.

I found a code snippet, which I totally not understood:

if (!Function.prototype.bind) {
  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)));   
        };
    nop.prototype   = self.prototype;
    bound.prototype = new nop();
    return bound;
  };
}

I know it checks if a function with the name bind is defined, and when not, define it.

But why it is checked on the prototype of the Function object ?

Why it is not a simple check of:

if(typeof bind != 'function')
astropanic
  • 10,800
  • 19
  • 72
  • 132
  • Because that's the purpose of that script, to polyfill (add missing functionality) on browsers that dont' support `Function.prototype.bind` – elclanrs Nov 10 '13 at 21:34
  • 1
    Bind can be used to set the value of `this` no matter what the invoking object is. You can use closures for this as well. The value of `this` is explained here: http://stackoverflow.com/a/16063711/1641941 – HMR Nov 11 '13 at 01:52

1 Answers1

2

Because bind is a class method on Objects of type Function, not a global function provided by Javascript.

musically_ut
  • 34,028
  • 8
  • 94
  • 106