Delegation in JavaScript

author: Krasimir Tsonev 2010-12-27 by Krasimir
in JavaScript
If you enjoy this, share it!
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();
Did you enjoy this?
Be sure to check out the other articles in the same category.

blog comments powered by Disqus