1

I read this, and I understand it, but, is there a way to attach a function to always execute a function alias on a specific scope, without the user of the function alias have to use the sort of clunky .apply stuff?

Community
  • 1
  • 1
Dhaivat Pandya
  • 6,499
  • 4
  • 29
  • 43

1 Answers1

2

You can use the new ECMAScript 5 .bind() method. An alternative implementation for browsers that don't support it (taken from the MDC documentation I linked to):

// Function.prototype.bind polyfill
if ( !Function.prototype.bind ) {

  Function.prototype.bind = function( obj ) {
    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 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;
  };
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143