Original link:http://www.cnblogs.com/Uncle-Keith/p/5834289.html
In a typical object-oriented language, such as Java, there is the concept of Class (Class), which is the template for the object, which is an instance of the class. In the JavaScript language system, however, there is no concept of class, and JavaScript is not based on ' class ', but rather through constructors (constructor) and prototype chains (prototype chains). In ES6, however, the concept of class is introduced as a template for objects that are closer to the traditional language. class
you can define a class by keyword. Basically, ES6 class
can be regarded as just a syntactic sugar, its most functions, ES5 can do, the new way of writing class
just let the prototype object writing more clearly, more like object-oriented programming syntax.
According to my habit, I will give the article directory before I write the article.
The following sections are categorized as follows:
1. A brief introduction to the constructor
2. Disadvantages of constructors
The role of 3.prototype properties
4. Prototype chain (prototype chain)
5.constructor Properties
The role of the 5.1:constructor attribute
6.instanceof operator
1. A brief introduction to the constructor
In one of my JavaScript's close relationships with the new command, the concept and features of the constructor are described in detail, the principle and usage of the new command, and so on, if the students are unfamiliar with the constructor, they can go to savor. Here is a brief review.
A constructor is a function that provides a template that generates an object and describes the basic structure of an object. A constructor that can generate multiple objects, each with the same structure. In general, a constructor is a template for an object, which is an instance of a constructor.
The features of the constructor are:
A: The first letter of the function name of the constructor must be capitalized.
B: Use the This object internally to point to the object instance that will be generated.
C: Use the new operator to call the constructor and return the object instance.
Look at one of the simplest examples.
1 function Person () {2 this.name = ' Keith ', 3 }4 5 var boy = new Person (); 6 Console.log ( Boy.name); ' Keith '
2. Disadvantages of constructors
All instance objects can inherit the properties and methods in the constructor. However, a property cannot be shared between the same object instance.
1 function Person (name,height) {2 this.name=name; 3 this.height=height; 4 this.hobby=function () {5 return ' watching movies '; 6 } 7 } 8 9 var boy=new person (' Keith ', girl=new); var (' Rascal ', 153) ; Console.log (boy.name); ' Keith ' Console.log (girl.name); ' Rascal ' Console.log (boy.hobby===girl.hobby); False
In the above code, a constructor person generates two object instances, boy and girl, and has two properties and a method. However, their hobby methods are not the same. That is, whenever you use new to call the constructor to put back an object instance, a hobby method is created. This is neither necessary nor wasteful, since all hobby methods are babyfaced and can be shared by two object instances entirely.
Therefore, the disadvantage of constructors is that properties or methods cannot be shared between object instances of the same constructor.
The role of 3.prototype properties
In order to solve the disadvantage that the property cannot be shared between the object instances of the constructor, JS provides the prototype property.
Each data type in JS is an object (except null and undefined), and each object inherits from another object, which is called a "prototype" (prototype) object, except for null, which does not have its own prototype object.
all properties and methods on the prototype object are shared by the object instance .
When an object instance is generated from a constructor, the prototype of the object instance points to the prototype property of the constructor. Each constructor has a prototype property, which is the prototype object of the object instance.
1 function Person (name,height) {2 this.name=name; 3 this.height=height; 4 } 5 6 Person.prototype.hobby=function () {7 return ' watching movies '; 8 } 9 var boy=new person (' Keith ', 180); One -to-one var girl=new person (' rascal ', 153); Console.log (boy.name); ' Keith ' Console.log (girl.name); ' Rascal ' Console.log (boy.hobby===girl.hobby); True
In the above code, if the hobby method is placed on a prototype object, then two instance objects share the same method. What I want you to understand is that for constructors, prototype is the property of the constructor, and for an object instance, prototype is the prototype object of the object instance. So prototype is a property and an object.
the properties of the prototype object are not properties of the object instance . The properties of an object instance are inherited from the property defined by the constructor, because there is a this keyword inside the constructor to point to the object instance that will be generated. The properties of an object instance are actually properties defined inside the constructor. As soon as you modify the properties and methods on the prototype object, the changes are immediately reflected on all object instances.
1 person.prototype.hobby=function () {2 return ' swimming '; 3 }4 console.log (boy.hobby===girl.hobby ); True5 Console.log (Boy.hobby ()); ' Swimming ' 6 console.log (Girl.hobby ()); ' Swimming '
In the above code, two object instances have changed after the hobby method of the prototype object has been modified. This is because the object instance is not a hobby method, it is the hobby method that reads the prototype object. That is, when an object instance does not have the property and method, it is looked up to the prototype object. If the instance object itself has a property or method, it does not look on the prototype object.
1 boy.hobby=function () {2 return ' play basketball '; 3 }4 console.log (Boy.hobby ()); ' Play basketball ' 5 Console.log (Girl.hobby ()); ' Swimming '
In the above code, when the hobby method of the Boy object instance is modified, the hobby method on the prototype object is not inherited. However, girl will still inherit the method of the prototype object.
To summarize:
A: The purpose of a prototype object is to define the properties and methods that are shared by all object instances.
B:prototype, for a constructor, it is a property, and for an object instance it is a prototype object.
4. Prototype chain (prototype chains)
The properties and methods of an object, which may be defined in itself, may also be defined in its prototype object. Since the prototype object itself is also an object for an object instance, it also has its own prototype, thus forming a prototype chain (prototype chain). For example, an object is a prototype of an object, an object a
b
is a b
c
prototype, and so on. At the top of the prototype for all objects, it is Object.prototype, the object that the prototype property of an object constructor points to.
Of course, the Object.prototype object also has its own prototype object, which is a null object without any properties and methods, and the null object does not have its own prototype.
1 console.log (object.getprototypeof (Object.prototype)); Null2 Console.log (Person.prototype.isPrototypeOf (Boy)) //true
The prototype chain (prototype chain) features:
A: When reading a property of an object, the JavaScript engine first looks for the property of the object itself, and if it cannot find it, go to its prototype and find it, if it is not, go to the prototype prototype. If it is not found until the topmost level, it is Object.prototype
returned undefined
.
B: If the object itself and its prototype define a property with the same name, the property of the object itself is read first, which is called "Overwrite" (overiding).
C: Level up in the prototype chain to find a property, the performance is affected. The properties that are being searched for in the higher-level prototype object, the greater the impact on performance. If you look for a property that does not exist, it will traverse the entire prototype chain.
Look at the concept may be more obscure, let's look at an example. But it's really important to understand the concept.
1 var arr=[1,2,3];2 Console.log (arr.length); Console.log (arr.valueof ()) //[1,2,3]4 console.log (arr.join (' | ' )) 1|2|3
In the above code, an array of arr, with three elements inside the array, is set. We did not add any properties and methods to the array, but we did not give an error when calling Length,join (), ValueOf ().
The length property is inherited from Array.prototype and belongs to a property on the prototype object. The Join method is also inherited from Array.prototype, which belongs to a method on the prototype object. The two methods are shared by all arrays. When the length property is not on the instance object, the prototype object is searched.
The valueof method is inherited from the Object.prototype. First, the ARR array is not a valueof method, so it is found on the prototype object Array.prototype. Then, you find that there is no valueof method on the Array.prototype object. Finally, it object.prototype the prototype object to find it.
Take a look at the properties and methods of the Array.prototype object and the Object.prototype object respectively.
1 console.log (Object.getownpropertynames (Array.prototype)) 2//["Length", "Tosource", "toString", " toLocaleString "," join "," reverse "," sort "," push "," pop "," Shift "," unshift "," splice "," concat "," slice "," lastIndexOf " , "IndexOf", "ForEach", "Map", "filter", "reduce", "reduceright", "some", "every", "find", "FindIndex", "Copywithin", "fil L "," entries "," Keys "," Values "," includes "," constructor "," $set "," $remove "]3 Console.log ( Object.getownpropertynames (Object.prototype)) 4//["Tosource", "toString", "tolocalestring", "ValueOf", "Watch", " Unwatch "," hasOwnProperty "," isprototypeof "," propertyisenumerable "," __definegetter__ "," __definesetter__ "," __ Lookupgetter__ "," __lookupsetter__ "," __proto__ "," constructor "]
I believe that you see here, to prototype or indefinitely. This is normal, after all, JS is more important and more abstract concept, can not be mastered so quickly, and then chew more than a few, perhaps master its essence. At some point, there is a living example, which may also be a problem that we will encounter. You can look at the JS constructor and the prototype object.
5.constructor Properties
prototype
Object has a constructor
property that defaults to prototype
the constructor where the object resides.
1 function A () {};2 console.log (a.prototype.constructor===a) //true
Note thatprototype is the property of the constructor, and constructor is the object that the constructor's prototype property points to, that is, the properties of the prototype object . Be careful not to confuse.
1 console.log (A.hasownproperty (' prototype ')); True2 Console.log (A.prototype.hasownproperty (' constructor '));//true
Because constructor
a property is defined on a prototype ( prototype)
object above, it means that it can be inherited by all instance objects.)
1 function A () {};2 var a=new a (); 3 4 Console.log (a.constructor); A () 5 console.log (a.constructor===a.prototype.constructor);//true
In the above code, a
it is an A
instance object of the constructor, but there is a
no property of its own contructor
, which is actually read the A property above the prototype chain .prototype.constructor
.
The role of the 5.1:constructor attribute
A: Identify which constructor the prototype object belongs to
1 function A () {};2 var a=new a (); 3 4 Console.log (a.constructor===a) //true5 Console.log ( A.constructor===array) //false
The above code indicates that using the constructor
property, a
the constructor of the instance object is determined A
to be, instead of Array
.
B: Create another instance from an instance
1 function A () {};2 var a = new A (); 3 var b = new A.constructor (); 4 console.log (b instanceof A) ; True
In the above code, the constructor a
is an A
instance object, and the .constructor
constructor can be called indirectly from a.
C: It is possible to call its own constructor
1 A.prototype.hello = function () {2 return new This.constructor (); 3 }
D: Provides a pattern for inheriting another constructor from a constructor function
1 function Father () {}2 3 function Son () {4 Son.height.constructor.call (this); 5 }6 7 Son.height = new Father ();
The above code, Father
and Son
all are constructors, in Son
the internal this
adjustment Father
, will form Son
Father
the effect of inheritance.
E: Since the constructor property is a prototype object and a constructor, it is important to pay attention to the problem of constructor when modifying the prototype object.
There are two workarounds, either to point the constructor property to the original constructor, or to add properties and methods on the prototype object only, to avoid instanceof distortion.
6.instanceof operator
instanceof
The operator returns a Boolean value that indicates whether the specified object is an instance of a constructor.
1 function A () {};2 var a = new A (); 3 Console.log (a instanceof a); True
Because instanceof is valid for objects on the entire prototype chain, the same instance object may return true for more than one constructor.
1 function A () {};2 var a = new A (); 3 Console.log (a instanceof a); True4 Console.log (a instanceof Object); True
Note that the Instanceof object can only be used for complex data types (arrays, objects, etc.) and cannot be used for simple data types (booleans, numbers, strings, etc.).
1 var x = [1];2 var o = {};3 var b = True;4 var c = ' string '; 5 console.log (x instanceof Array);
//true6 console.log (o instanceof Object); True7 Console.log (b instanceof Boolean); False8 Console.log (c instanceof String); False
Also, null and undefined are not objects, so instanceof always returns false.
1 console.log (null instanceof Object); False2 console.log (undefined instanceof Object); False
With the instanceof
operator, you can also skillfully solve the problem of calling the constructor and forgetting to add new
the command.
1 function Keith (name,height) {2 if (! This instanceof Keith) {3 return new Keith (name,height); 4 }5 this.name = name;6 this.height = height;7 }
In the above code, the instanceof operator is used to determine whether the this keyword in the function body points to an instance of the constructor Keith, and if not, to forget the Add New command, at which point the constructor returns an object instance to avoid unexpected results.
For the time being confined to the space, this is briefly introduced here.
I'll talk about some of the native methods of the prototype (prototype) object in the next share, such as object.getprototypeof (), object.setprototypeof (), and the comparison of getting native object methods.
Finish.
Thank you for reading.
A detailed description of the prototype attribute in JavaScript