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')
2
  • Because that's the purpose of that script, to polyfill (add missing functionality) on browsers that dont' support Function.prototype.bind Commented Nov 10, 2013 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: stackoverflow.com/a/16063711/1641941 Commented Nov 11, 2013 at 1:52

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that was the kind of explanation I was seeking.
Glad to have been of help. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.