I have been studying js recently and have many questions. It is confused by the prototype. The question comes from:
The Code is as follows:
Function foo {
This. name = 'foo ';
}
Alert (foo. prototype = Function. prototype); // false. At that time, I never figured out why the prototype of foo is not Function. prototype.
The following example assumes that o. prototype = Function. prototype should be true:
The Code is as follows:
Function foo (){
This. name = 'foo ';
}
Function. prototype. sayHello = function (parent ){
Alert ('hello ');
};
Foo. sayHello (); // alert 'hello'
After I added a sayHello method to Function. prototype, foo also obtained sayHello from the prototype. With the debugger to observe, check the information (including ECMA-262 http://dmitrysoshnikov.com/ecmascript/chapter-5-functions/ and JavaScript the good parts Chapter 5 5.1 pseudo doclassical), found that foo. prototype definition is as follows:
This. prototype = {constructor: this}; // foo. prototype = {constructor: foo };
By the way, we did the following tests:
Alert (foo = foo. prototype. constructor); // true
So what is foo. prototype? This is closely related to the new keyword. Let's talk about what new foo () has done.
Var obj ={}; // defines a new Object
Obj. [[prototype] = this. prototype;
// Note 1: here this is foo, foo. prototype, which is useful now. assign a value to the obj prototype and use [[prototype] to represent its prototype.
// NOTE 2: obj does not have the prototype attribute. It is probably useless.
Var other = this. apply (obj, arguments); // make obj. name = 'foo', that is, obj runs the foo function once as this.
Return (typeof other = 'object' & other) | that; // If the foo function returns an object, this object is returned; otherwise, obj is returned.
In this way, it is clear that during the new foo () process, foo creates an object and serves as its constructor, while foo. prototype is used as the prototype of the new object.
Foo. prototype can be added to any method or changed to any object, without fear of modifying Function. prototype (Function. prototype is the prototype of all functions );
This. prototype = {constructor: this}; indicates that, without manually specifying foo. prototype, js specifies a default prototype for the new object.