各大JS框架庫都有一套基於JS原型對象的擴展,很多擴展方法能提高方便的用途,最普通的就是封裝作用域這類方法了:下面來看幾個例子,都是模仿Extjs和Prototype的源碼
HL.append = function(destination, source){
for (var o in source){
destination[o] = source[o];
}
return destination;
};
HL.append(Function.prototype, {
//改變 當前函數的作用域以及參數
delegate : function(scope){
var method = this ,
arglist = Array.prototype.slice.call(arguments, 1 );
return function(){
var callargs = Array.prototype.slice.call(arguments, 0 ).concat(arglist);
return method.apply(scope || method || window, callargs);
};
},
//鏈接當前函數的作用域至指定參數
defer : function(time, scope, args){
var slice = Array.prototype.slice,
method = this ,
argList = slice.call(arguments, 2 );
if(time > 0)return setTimeout(this.delegate(scope, argList) , time);return method();
},intercept : function(fn, scope){var slice = Array.prototype.slice,method = this,argList = slice.call(arguments, 2);return function(){var callargs = slice.call(arguments,0).concat(argList);if(fn.apply(object || method || window, callargs) === false){return method.apply(object || method || window, callargs);}return false;};}});
先看看HL.append,這是一個復制對象屬性的功能方法,並不是類繼承操作,能方便的復制source對象內的屬性至destination對象中。
然后是對Function的擴展,這里添加了兩個原型方法,這樣以后所有的函數都能調用它們。delegate是一個改變函數作用域的方法,正所謂閉包無處不在,它返回一個新的函數,源函數在此以apply方式運行,作用域變成指定的參數,並且新方法鏈接了新的參數。
defer是一個定時器方法,在具備delegate所有功能的同時,加入了一個定時器,在Time時間之后運行源函數.
intercept 就是一個標准的攔截器,能在源函數運行之前調用參數fn,若返回結果為true則運行原函數。這也是Spring中典型的AOP模式,Javascript靈活性極高,要實現諸如Spring的注入與AOP可謂輕車熟路。
理解上述代碼能讓你更好的掌握javascript中的閉包知識,以及函數的apply調用模式,並且意識到arguments並非真正的數組,調用數組方法需要特殊處理哦。晚安、、、、、、、、
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。