Home > Web Front-end > JS Tutorial > Questions about the prototype and prototype attributes of function foo_javascript skills

Questions about the prototype and prototype attributes of function foo_javascript skills

WBOY
Release: 2016-05-16 18:15:56
Original
1045 people have browsed it

The confusion comes from:

Copy code The code is as follows:

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:
Copy code The code is as follows:

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.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template