Search code examples
javascriptinheritanceprototype-chain

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


Trying to define a hashCode method on Object.prototype as well as String.prototype and Number.prototype. I'm defining the prototype methods using:

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

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

When I create a number or string with any of ('', new String(), 3, new Number()), and call hashCode on the instance, the Object.prototype.hashCode method always runs instead of String.prototype.hashCode or Number.prototype.hashCode.

What's wrong?


Solution

  • Make the property descriptor writable: true or it will be inherited as non-writable when writing that property on objects that inherit it. http://jsfiddle.net/5ox1a0f2 – squint

    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()