Search code examples
javascriptprototype-programming

Modify build-in Object prototype


String.prototype = new Number();
console.log(String.prototype.__proto__ === Number.prototype);//return false

why i cant change the prototype chain of bulid-in Object.


Solution

  • This is because the prototype property of built-in constructors1 is non-writable (also non-configurable and non-enumerable).

    See the property attributes:

    Object.getOwnPropertyDescriptor(String, 'prototype');
    
    /*
    configurable: false,
    enumerable: false,
    writable: false
    */
    

    This is described in each built-in constructor, for the String.prototype property see :

    15.5.3.1 String.prototype

    ...

    This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

    1: by "built-in constructor" I refer to the constructor functions defined on the global object: String, Number, Boolean, Object, Array, Function, Date, RegExp, Error (and other NativeError types).