As far as I see, JS has some sort of protection from accidential rewriting of global function's prototype.
For example, here it's not a global constructor function. Everything works fine.
function func() { };
function Constructor() {
this.name = 'Luisa';
this.surname = 'Li';
this.age = 48;
};
Constructor.prototype = func;
let obj = new Constructor;
let obj2 = new Constructor;
console.log(obj.__proto__ == func); //true
console.log(obj.__proto__ == func); //true
But here I'm trying to work with prototype through global constructor function Object
. Nothing is working.
function func2() { };
Object.prototype = func2;
let a = {};
console.log(a.__proto__ == func2); //false
So, is there some kind of protection in JS from rewriting the global prototype? Cause in some cases JS allows us to work straight with global constructor functions (add global methods, for example).
If you log the property descriptor object of the Object.prototype
property
console.log(Object.getOwnPropertyDescriptor(Object, 'prototype'));
you will notice that, its:
As Object.prototype
is not-writable, this means that you cannot overwrite the Object.prototype
but you can, however, add methods (not recommended) to the object pointed to by the Object.prototype
property.
In strict mode, assigning to a non-writable property throws an error but in non-strict mode, it fails silently.
Note: You should use Object.setPrototypeOf()
method to set the prototype of an object and use Object.getPrototypeOf()
method to get it.