Javascript Examples

  Javascript Examples


2016-09-13



	
	
	
		
	
	
	
	摘自《Javascript权威教程》

Monkey Path:

12345678910> function trace(o, m){> var original = o[m];> o[m] = function(){> console.log(new Date(), “Entering:”, m);> var result = original.apply(this, arguments);> console.log(new Date(), “Exiting:”, m);> return result;> };> }>

上面这种方法,更像是装饰器——动态添加了函数对象原本不支持的职责,缺不破坏函数本身。

Bind方法:

123456789101112131415> if(!Function.prototype.bind) {> Function.prototype.bind = function(o /*, args */){> // 将this 和arguments 的值保存至变量中> // 以便后面嵌套的函数中可以使用它们> var self = this, boundArgs = arguments;> > return function() {> var args = [], i;> for(i=1; i < boundArgs.length; i++) args.push(boundArgs[i]);> for(i=0; i < arguments.length; i++) args.push(arguments[i]);> return self.apply(o, args);> };> };> }>

上面是对使用ECMA-Script3 标准对ECMA-Script5标准的扩展。支持动态绑定,就像jQuery中的on方法。

JavaScript

coding