Doubts come from:
Copy Code code as follows:
function Foo {
this.name = ' Foo ';
}
Alert (Foo.prototype = = Function.prototype); False I was wondering why Foo's prototype was not function.prototype.
The following example lets me take it for granted that O.prototype = = Function.prototype should be true:
Copy Code code as follows:
function foo () {
this.name = ' Foo ';
}
Function.prototype.sayHello = function (parent) {
Alert (' Hello ');
};
Foo.sayhello (); Alert ' Hello '
When I added a SayHello method to Function.prototype, Foo also got SayHello from the prototype. Look at it with the debugger and check the data (including ECMA-262 http://dmitrysoshnikov.com/ecmascript/chapter-5-functions/and the JavaScript good parts Chapter Fifth 5.1 pseudoclassical), found that the definition of Foo.prototype is as follows:
This.prototype = {Constructor:this}; Here is Foo.prototype = {Constructor:foo};
The following tests were done by the way
Alert (foo = = Foo.prototype.constructor); True
What the hell is that foo.prototype? This is closely related to the new keyword. Tell me what new Foo () did.
var obj = {}; Define a new object
Obj.[[prototype]] = = This.prototype;
Note 1: This here is foo,foo.prototype at this time, giving the prototype of obj a value, where [[[prototype]] represents its prototype
Note that 2:obj is not prototype attribute, it is not a good guess.
var other = this.apply (obj, arguments); This lets obj.name = ' foo ', that is, obj run over the Foo function as this
Return (typeof, other = = ' object ' && other) | | that; If the Foo function returns an object, the object is returned, or obj is returned.
So it's clear that when new Foo (), Foo creates an object and acts as its constructor, and Foo.prototype is used as a prototype for the new object.
Foo.prototype can add any method, or change to arbitrary object, not afraid to modify the Function.prototype (Function.prototype is the prototype of all functions);
This.prototype = {Constructor:this}; The meaning is that, without manually specifying the Foo.prototype, JS specifies a default prototype to the new object.