The confusion comes from:
function foo {
this. name = 'foo';
}
alert(foo.prototype === Function.prototype ); //false. At that time, I never understood why the prototype of foo was not Function.prototype.
The following example makes me take it for granted that o.prototype === Function.prototype should be true:
function foo() {
this.name = 'foo';
}
Function.prototype.sayHello = function (parent) {
alert('hello');
};
foo.sayHello(); //alert 'hello'
When I give After Function.prototype adds a sayHello method, foo also gets sayHello from the prototype. I observed it with the debugger and checked the information (including ECMA-262 http://dmitrysoshnikov.com/ecmascript/chapter-5-functions/ and "JavaScript the good parts" Chapter 5 5.1 Pseudoclassical) and found foo.prototype The definition is as follows:
this.prototype = {constructor: this}; //Here is foo.prototype = {constructor: foo};
By the way, I did the following test
alert(foo === foo. prototype.constructor); //true
What exactly is foo.prototype? This is closely related to the new keyword. Just talk about what new foo() does.
var obj = {}; //Define a new Object
obj.[[prototype]] == this.prototype;
//Note 1: this here is foo, foo.prototype This is where it comes in handy. Assign a value to the prototype of obj. Here, use [[prototype]] to represent its prototype
//Note 2: obj does not have a prototype attribute, so it is probably useless
var other = this.apply(obj, arguments); //Let obj.name = 'foo', that is, obj is run as this. foo function
return (typeof other === 'object' && other) || that ; //If the foo function returns an object, return the object, otherwise return obj.
This makes it very clear. When new foo(), foo creates an object and serves as its constructor, and foo.prototype is used as the prototype of the new object.
foo.prototype can add any method or change it to any object without fear of modifying Function.prototype (Function.prototype is the prototype of all functions);
this.prototype = {constructor: this}; The meaning is that without manually specifying foo.prototype, js specifies a default prototype for the new object created by new.