I have been studying js recently and have many questions. It is confused by the prototype. The question comes from:
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:
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 Objectobj. [[prototype] = this. prototype; // Note 1: here this is foo, foo. prototype is useful at this time. assign a value to the obj prototype. [[prototype] indicates its prototype. // NOTE 2: obj has no prototype attribute, it is probably useless. var other = this. apply (obj, arguments); // make obj. name = 'foo', that is, obj runs the foo function return (typeof other = 'object' & other) as this. | 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.