javascript 给类型添加方法
本文关于javascript的内容部分借用《javascript语言精粹》这本书!
//给类型添加方法//js允许给语言的基本类型添加方法//举例 添加一个方法到Function.prototype 使得这个方法对所有函数可用Function.prototype.method = function ( name, func ){this.prototype[name] = func;return this;}//要注意构建方法时, 给基本类型添加方法时, 新的方法会赋予到所有的值,(包括存在)//所以要尽量避免添加到已存在的值, 安全的做法就是要检测是否有要添加的属性Function.prototype.method = function ( name, func ){if( ! this.prototype[name] ){this.prototype[name] = func;} return this;}//添加一个test方法//var a = Function.method('test', (function(){alert('test')}));//a.test();//Function.test();//在举例 , 都知道js没有单独的整数类型, 有的时候提取数字忠的整数部分是必要的。//js本身提供取整的方法 Math.ceil Math.floor 这个两个函数的区别。 用一句话说就是ceil 进一, floor退一//这样取整的话 需要判断正负 尝试考虑 3.6 -3.6 3.3 -3.3得值。//可以改善它Number.method('integer', function(){return Math[this < 0 ? 'ceil' : 'floor'](this)});document.writeln((3.3).integer());//举例3 构建一个字符 过滤左右空格的函数 并添加到字符串的函数对象去//添加了一个正则 过滤掉两则都有空格的情况String.method('trim', function(){return this.replace(/^\s+|\s+$/g, '');})var a = " nihao ".trim();var b = " nihao ";document.writeln(a.length-b.length);