林秀栋的技术博客

设计模式(十四) 职责链模式

//对于对象结构的元素,在不改变对象的前提下访问结构中元素的新方法
//js原生的call和apply就能实现改功能
//比如下面在不改变数组splice和push方法的前提下,给对象添加这些方法

var Visitor = (function(){
	return {
		splice: function(){
			var args = Array.prototype.splice.call(arguments, 1);
			return Array.prototype.splice.apply(arguments[0], args);
		},
		push: function(){
			var len = arguments[0].length || 0;
			var args = this.splice(arguments, 1);
			arguments[0].length = len + arguments.length - 1;
			return Array.prototype.push.apply(arguments[0], args);
		}
	}
})();

var a = new Object();
console.log(a.length);
Visitor.push(a, 1, 2, 3);
console.log(a.length);