1. What is a prototype? What is the prototype chain?
A prototype is a prototype object that represents the relationship between types;
The prototype chain refers to the inheritance between objects in JavaScript by pointing to the parent class object through the prototype object, until it points to object objects, thus forming a chain that the prototype points to, which is called the prototype chain.
Example:
Student-->person-->object: The student inherits This kind, the person this class inherits the object class;
<span style= "FONT-SIZE:14PX;" >
var person=function () {
this.age= "Anonymous"
}; var student=function () {}; Creates an inheritance relationship, prototype executes an instance object of person student.prototype=new person ();
</span>
Five prototype rules:
1, all reference types (arrays, objects, functions), all have object attributes, you can freely extend the properties (except "null");
2, all reference types have a _proto_ attribute, called implicit prototype, the attribute value is an ordinary object;
3, all functions, have a prototype attribute, called explicit prototype, attribute value is a common object;
4. The _proto_ property of all reference types, the value of the prototype attribute that points to its constructor;
<! DOCTYPE html>"Utf-8"> <title></title> <script>//All reference types have object properties varobj = {}; OBJ.A= -; vararr = []; ARR.A= -; function fn () {} Fn.a= -; //All reference types have an implicit prototypeConsole.log (obj.__proto__); Console.log (arr.__proto__); Console.log (fn.__proto__); //all functions have a prototype propertyConsole.log (Fn.prototype); //All reference types, the __proto__ property value points to the "prototype" property value of its constructorConsole.log (obj.__proto__ = = =Object.prototype); </script> 5, when trying to get a property of an object, if not, will look for it in the _proto_, that is, go to its constructor prototype.
<! DOCTYPE html>"Utf-8"> <title></title> <script>//constructor Functionfunction Foo (name,age) { This. Name =name; } Foo.prototype.alerName=function () {alert ( This. Name); } //Create an instance varf =NewFoo ('Zhangsan'); F.printname=function () {Console.log ( This. Name); } //TestF.printname (); F.alername (); </script> Again for example:
The dog class inherits the animal class and then owns the animal eat method (an example of very low)
<script type= "Text/javascript" > function Animal () { this.eat = function () { console.log ("Animal eat "); } } function Dog () { This.bark = function () { console.log ("Dog bark") } } dog.prototype = new Animal () ; var Hashiqi = new Dog (); Hashiqi.eat (); Animal eat hashiqi.bark (); Dog Bark </script>
Examples of close combat (an example of a package DOM query):
Be very careful about the location of JavaScript <! DOCTYPE html>Prototypes and prototype chains in JavaScript