向Object / Number / String原型添加方法

时间:2013-08-22 20:28:23

标签: javascript

声明

  • 这个帖子应该可以帮助遇到类似问题的其他人,以及检查是否有更好的解决方案。我将附上我自己的解决方案,但欢迎提出想法和改进(除了使其更通用)。
  • 我知道,一般来说,扩展内置对象是一个坏主意。因此,对这个主题的假设是有充分的理由而无法绕过它。

方案

作为开发人员,我想向所有Javascript对象添加方法someMethod,其中ObjectNumberString的实现方式不同。

我希望解决方案符合以下验收标准:

  • A)解决方案适用于浏览器
    • A1)如果脚本在严格的上下文中使用,解决方案将以严格模式运行
    • A2)解决方案在非严格模式下工作,因为'use strict';将在压缩过程中删除,例如YUI Compressor [1]
  • B)解决方案适用于node.js
    • B1)解决方案以严格模式工作(原因见A1)
    • B2)解决方案在非严格模式下工作的原因与B2相同,加上node.js中的严格模式无法在功能级别激活[2]
  • C)我希望允许其他对象覆盖此方法
  • D)如果可能,我想控制方法是否出现在for .. in循环中以避免与其他库发生冲突
  • E)解决方案实际上应该修改原型。

[1] Minfication removes strict directives
[2] Any way to force strict mode in node?

2 个答案:

答案 0 :(得分:1)

我自己的解决方案

在试图解决这个问题时,我遇到了一些导致一个或另一个接受标准破裂的问题(例如[1]中描述的问题)。过了一段时间,我想出了以下解决方案,这似乎对我有用。当然,这可以用更通用的方式编写。

(function () {
    'use strict';

    var methodName = 'someMethod',
        /** Sample method implementations */
        __someMethod = {
            'object': function () {
                var _this = this.valueOf();

                return ['Object'].concat( Array.prototype.slice.call( arguments ) );
            },

            'number': function () {
                var _this = this.valueOf();

                return ['Number'].concat( Array.prototype.slice.call( arguments ) );
            },

            'string': function () {
                var _this = this.valueOf();

                return ['String'].concat( Array.prototype.slice.call( arguments ) );
            },

            'boolean': function () {
                var _this = this.valueOf();

                return ['Boolean', _this];
            }
        };

    if( Object.defineProperty ) {
        Object.defineProperty( Number.prototype, methodName, {
            value: __someMethod['number'],
            writable: true
        } );

        Object.defineProperty( String.prototype, methodName, {
            value: __someMethod['string'],
            writable: true
        } );

        Object.defineProperty( Boolean.prototype, methodName, {
            value: __someMethod['boolean'],
            writable: true
        } );

        Object.defineProperty( Object.prototype, methodName, {
            value: __someMethod['object'],
            writable: true
        } );
    } else {
        Number.prototype[methodName] = __someMethod['number'];
        String.prototype[methodName] = __someMethod['string'];
        Boolean.prototype[methodName] = __someMethod['boolean'];
        Object.prototype[methodName] = __someMethod['object'];
    }
})(); 

编辑:我更新了解决方案,为[1]中提到的问题添加解决方案。即它是行(例如)var _this = this.valueOf();。如果使用

,原因就变得清晰了
'number': function (other) {
    return this === other;
}

在这种情况下,你会得到

var someNumber = 42;
console.log( someNumber.someMethod( 42 ) ); // false

当然,这不是我们想要的(同样,原因在[1]中说明)。因此,您应该使用_this代替this

'number': function (other) {
    var _this = this.valueOf();
    return _this === other;
}

// ...

var someNumber = 42;
console.log( someNumber.someMethod( 42 ) ); // true

[1] Why does `typeof this` return "object"?

答案 1 :(得分:1)

创建一个包装器对象(注意这只是一个例子,它不是很健壮):

var $ = (function(){
  function $(obj){
    if(!(this instanceof $))
        return new $(obj);

    this.method = function(method){
        var objtype = typeof obj;
        var methodName = method + objtype[0].toUpperCase() + objtype.substr(1);
        typeof _$[methodName] == 'function' && _$[methodName].call(obj);
    }
  }

  var _$ = {};

  _$.formatNumber = function(){
    console.log('Formatting number: ' + this);
  }

  _$.formatString = function(){
    console.log('Formatting str: "' + this + '"');
  }

  _$.formatObject = function(){
    console.log('Formatting object: ');
    console.log(JSON.stringify(this));
  }

  return $;
})();

用法:

var num = 5;
var str = 'test';
var obj = {num: num, str: str};

var $num = $(num);
$num.method('format');

$(str).method('format');
$(obj).method('format');

Demo