Check out "Do you speak JavaScript?" - my latest video course on advanced JavaScript.
Language APIs, Popular Concepts, Design Patterns, Advanced Techniques In the Browser

Delegation in JavaScript

I think that the delegation is an important part of every programming language. It is also possible in JavaScript.

function delegate(scope, method) {
    if (arguments.length > 2) {
      var args = [];
      var numOfArgs = arguments.length;
      for (var i = 2; i < numOfArgs; i++) {
        args.push(arguments[i]);
      }
      return function () {
        return method.apply(scope, args);
      }
    } else {
      return function () {
        return method.call(scope);
      }
    }
  }

What you have to do is to pass the scope, i.e. the class that contains the method, and of course the method itself. Here is the full example:

function delegate(scope, method) {
    if (arguments.length > 2) {
      var args = [];
      var numOfArgs = arguments.length;
      for (var i = 2; i < numOfArgs; i++) {
        args.push(arguments[i]);
      }
      return function () {
        return method.apply(scope, args);
      }
    } else {
      return function () {
        return method.call(scope);
      }
    }
  }
  var Class = {};
  Class = function () {
    this.text = "my name is ";
  }
  Class.prototype = {
    showName: function (nameStr) {
      alert(this.text + nameStr);
    }
  }
  var obj = new Class();
  var func = delegate(obj, obj.showName, "Krasimir");
  func();
If you enjoy this post, share it on Twitter, Facebook or LinkedIn.