您的位置:首页 > 其它

HighCharts源码学习---扩展函数wrap和扩展对象 extendClass

2015-12-27 14:24 302 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: