Home >Web Front-end >JS Tutorial >A more difficult concept to understand in JavaScript-prototype
Prototype is a difficult concept to understand in JavaScript. There are many attributes related to prototype. Objects have "prototype" attributes, function objects have "prototype" attributes, and prototype objects have "constructor" attributes. .
1. First introduction to prototype
In JavaScript, the prototype is also an object. The property inheritance of the object can be realized through the prototype. JavaScript objects all contain a "[[Prototype]]" internal property. This attribute corresponds to the prototype of the object.
"[[Prototype]]" is an internal property of the object and cannot be accessed directly. So in order to conveniently view the prototype of an object, Firefox and Chrome provide the non-standard (not supported by all browsers) __proto__ accessor (ECMA introduced the standard object prototype accessor "Object.getPrototype(object)") . The prototype object of JavaScript also contains a "constructor" attribute, which corresponds to the constructor that creates all instances pointing to the prototype.
2. Rules
In JavaScript, each function has a prototype attribute. When a function is used as a constructor to create an instance, the prototype attribute value of this function will be assigned to all object instances as the prototype (that is, the `__proto__` attribute of the instance is set), that is, the value of all instances The prototype refers to the prototype attribute of the function. (****`Only function objects will have this attribute!`****)
The process of new is divided into three steps
?
var p = new Person('Zhang San',20);
1. var p={}; Initialize an object p.
2. p._proto_=Person.prototype;, set the __proto__ attribute of object p to Person.prototype
3. Person.call(p,"Zhang San",20);Call the constructor Person to Initialize p. Regarding the use of call/apply
The above is the detailed content of A more difficult concept to understand in JavaScript-prototype. For more information, please follow other related articles on the PHP Chinese website!