author: Krasimir Tsonev

Hi there, I'm . Senior front-end engineer with over 13 years of experience. I write, speak and occasionally code stuff. Follow me on Twitter, GitHub, Facebook or LinkedIn

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. Or maybe comment below: