为什么 Object 原型方法会覆盖 JavaScript 中的 String 和 Number 原型方法?

Why would an Object prototype method override String and Number prototype methods in JavaScript?

正在尝试在 Object.prototype 以及 String.prototypeNumber.prototype 上定义 hashCode 方法。我正在使用以下方法定义原型方法:

Object.defineProperty(Object.prototype, 'hashCode', {
  value:function() {/*code*/},
  enumerable:false
});

String.prototype.hashCode = function() {/*code*/};
Number.prototype.hashCode = function() {/*code*/};

当我使用 (''new String()3new Number()) 创建一个数字或字符串时,并调用 hashCode例如,Object.prototype.hashCode 方法总是代替 String.prototype.hashCodeNumber.prototype.hashCode.

运行

怎么了?

使 属性 描述符可写:true 否则当在继承它的对象上写入 属性 时它将被继承为不可写。 http://jsfiddle.net/5ox1a0f2 – 斜视

Object.defineProperty(Object.prototype, 'hashCode', {
  value:function() {console.log('object')},
  enumerable:false,
  writable:true
});

String.prototype.hashCode = function() {console.log('string')};
Number.prototype.hashCode = function() {console.log('number')};

4..hashCode()

混合使用 属性 定义和 属性 赋值会导致此类问题。

如果您也在 String.prototypeNumber.prototype 中使用 属性 定义,它会起作用:

Object.defineProperty(Object.prototype, 'hashCode', {
  value: function() {console.log('object')},
  enumerable: false
});
Object.defineProperty(String.prototype, 'hashCode', {
  value: function() {console.log('string')},
  enumerable: false
});
Object.defineProperty(Number.prototype, 'hashCode', {
  value: function() {console.log('number')},
  enumerable: false
});
(4).hashCode(); // "number"
('').hashCode(); // "string"

但是,如果您只使用 属性 定义,因为您不想要可枚举性,但又不关心可配置性或可写性,那么通过赋值定义方法可能更方便,然后重新定义可枚举性:

Object.prototype.hashCode = function() {console.log('object')};
String.prototype.hashCode = function() {console.log('string')};
Number.prototype.hashCode = function() {console.log('number')};
Object.defineProperty(Object.prototype, 'hashCode', {enumerable: false});
Object.defineProperty(String.prototype, 'hashCode', {enumerable: false});
Object.defineProperty(Number.prototype, 'hashCode', {enumerable: false});
(4).hashCode(); // "number"
('').hashCode(); // "string"