通过Object.prototype扩充功能,增加对所有对象都可用的方法

来源:互联网 发布:cocos2d-js教程 编辑:程序博客网 时间:2024/06/05 16:36

通过给 Object.prototype增加方法可以让该方法对所有对象都可用

举例:对 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;}

使用方法举例1:
给 Number.prototype增加一个integer方法,该方法可根据数字的正负来判断是使用Math.ceil 还是 Math.floor方法提取数字中的整数部分:

Number.method ('integer', function (){    return Math[ this < 0 ? 'ceil' : 'floor' ](this);});document.write( (-11 / 3).integer() ); //-11/3取整得-3

使用方法举例2:
给String.prototyp增加一个移除字符串收尾空白的方法:

String.method('trim', function(){    return this.replace(/^\s+|\s+$/g, '');})
阅读全文
0 0
原创粉丝点击