Skip to content Skip to sidebar Skip to footer

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 class

Solution 1:

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 asx.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.

Solution 2:

I have to point it out that:the prototype of Function is Function.prototype, but a specific function like foo, it's prototype is not Function.prototype.

Function.prototype is a callable object, it is a "function" (typeof Function.prototype).foo.prototype is an "object". When you Function constructor construct a function like foo, it runs a code: this.prototype={constructor:this} (This is from "The JavaScript: good parts", Douglas Crockford); i.e foo.prototype={constructor:foo}.

Post a Comment for "Why Function.prototype Cannot Be Modified ?"