Bardelman Bardelman - 4 months ago 11
Javascript Question

Why Function.prototype cannot be modified ?

in the Function.prototype page it's written this :


Function objects inherit from Function.prototype. Function.prototype
cannot be modified.


Or in javascript there are no classes but the Inheritance and the prototype chaining in which constructors are actually functions :

function AclassName(){
return 2;
}

// AclassName ---> Function.prototype ---> Object.prototype ---> null


and i think it's always possible to extend the class prototype's like :

AclassName.prototype.color = "somevlue";


So what does it mean that i can't be modified ?

Answer

Everything in JS has a prototype (even if it's null). So, the prototype of an actual function is Function.prototype.

When you assign or modify AclassName.prototype in your example, you're setting the prototype for instances of AclassName. Note that the prototype of an object x is not the same as x.prototype. That .prototype is used for setting the prototype that will be used for instances of x, if x is used as a constructor.

To put it another way:

Your function AClassName, declared with function AClassName () {}, is an object of class Function, so it inherits from Function.prototype.

If you instantiate that class:

var myInstance = new AClassName();

Then myInstance is an object of class AClassName, so it inherits from AClassName.prototype.

So to answer the root of your question: Function.prototype cannot be modified, because it's a core part of the language and being able to change it might introduce performance or security issues. However, you are totally at liberty to modify the prototypes of your own classes.