问题
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 ?
回答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 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.
回答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}
.
来源:https://stackoverflow.com/questions/34897762/why-function-prototype-cannot-be-modified