HighCharts源碼學習---擴展函數wrap和擴展對象 extendClass

Highcharts.wrap在原函數的基礎上擴展原函數

 /**
     * Wrap a method with extended functionality, preserving the original function
     * @param {Object} obj The context object that the method belongs to
     * @param {String} method The name of the method to extend
     * @param {Function} func A wrapper function callback. This function is called with the same arguments
     * as the original function, except that the original function is unshifted and passed as the first
     * argument.
     */

var wrap = Highcharts.wrap = function (obj, method, func) {
     //備份原函數
     var proceed = obj[method];
     obj[method] = function() {
     	//拷貝一份實參
     	var args = Array.prototype.slice.call(arguments);
     	//將原函數的引用放到第一個入參
     	args.unshift(proceed);
     	//保持上下文調用func
     	func.call(this, args);
     }
}
利用wrap重新封裝parseInt()


  wrap(window, parseInt, function(proceed, str, scale) {
     	if(typeof str === 'number') return proceed.call(this, str);

     	var hexChars = 'abcdef', decChars = '9';
     	var hasHex = false,hasDec = false,i = 0, len = str.length;

     	if(!scale) {
     		if(str.charAt(0) === '0') {
     			if(str.charAt(1) === 'x') {
     				return proceed.call(this, str, 16);
     			}
     			else {
     				for(i = 0;i < len; i++) {
     					var char  = str.charAt(i).toLowerCase();
     					if(hexChars.indexOf(char) > -1) hasHex = true;
     					if(decChars.indexOf(char) > -1) hasDec = true;
     				}
     			}
     			if(hasHex) {
     				return procced.call(this, str, 16);
     			}else if(hasDec) {
     				return procced.call(this, str, 10);
     			} else {
     				return procced.call(this, str, 8);
     			}
     		}

     		return procced.call(this, str, 10);
     	}

     })

Highcharts擴展原型對象

 /**
     * Extend a prototyped class by new members
     * @param {Object} parent
     * @param {Object} members
     */
    function extendClass(Parent, members) {
        var object = function () {
        };
        object.prototype = new Parent();
        extend(object.prototype, members);
        return object;
    }





發佈了117 篇原創文章 · 獲贊 25 · 訪問量 44萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章