我自己的解决方案
在尝试解决这个问题时,我遇到了一些问题,导致一个或另一个接受标准被打破(例如 [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"?