本文是《JavaScript语言精粹》的读书笔记,内容来源于第4章“函数”“扩充类型的功能”。
JavaScript允许给基本类型(如String、Number
等)扩充功能,可以通过给Function.prototype
增加方法使得该方法对所有函数可用:
//为Function.prototype增加method方法,方便以后创建新的方法
Function.prototype.method = function(name,func){
if(!this.prototype[name]){ //没有该方法时才添加
this.prototype[name] = func;
}
return this;
};
//为Number.prototype增加一个integer方法,用于提取数字中的整数部分
Number.method('integer',function(){
return Math[this < 0 ? 'ceil' : 'floor'] (this);
});
//为String添加移除字符串首尾空白的方法
String.method('trim',function(){
return this.replace(/^\s+|\s+$/g,'');
});
首先纠正书中一个笔误,部分版本中可能将“ceil
”函数误写为“ceiling
”。
书中阐述:“通过给Function.prototype
增加method
方法,下次给对象增加方法时就不必键入prototype
,省掉了一点麻烦。”
如果不希望增加的方法对所有函数可用,而是对特定类型增加方法(如只对Number类型增加integer方法),示例如下:
Number.prototype.method = function integer(){
return Math[this < 0 ? 'ceil' : 'floor'] (this);
}; //不能省略此处的分号
console.log((-10/3).method()); //测试为Number添加的integer方法
console.log((-10/3).integer()); //测试为Number添加的integer方法
或者:
Number.prototype.integer = function (){
return Math[this < 0 ? 'ceil' : 'floor'] (this);
}; //不能省略此处的分号
console.log((-10/3).integer()); //测试为Number添加的integer方法