Explain the prototype attribute in JavaScript (recommended) _javascript tips

Source: Internet
Author: User
Tags object object hasownproperty es6 class

In a typical object-oriented language, such as Java, there are classes (class) concepts, classes are templates of objects, objects are instances of classes. But in the JavaScript language system, there is no concept of class, JavaScript is not based on ' class ', but is implemented through constructors (constructor) and prototype chains (prototype chains). But in ES6, it provides a more close to the traditional language, introduces the class (class) concept, as the object template. The class keyword allows you to define classes. Basically, the ES6 class can be regarded as just a grammatical sugar, most of its functions, ES5 can be done, the new class writing is only to make the prototype object more clear, more like the syntax of object-oriented programming.

According to my custom, I will give the article catalogue before writing the article.

The following sections are categorized as follows:

1. A brief introduction to the constructor function

2. Disadvantages of constructors

The role of 3.prototype properties

4. Prototype chain (prototype chain)

5.constructor Properties

The role of 5.1:constructor properties

6.instanceof operator

1. A brief introduction to the constructor function

In one of my JavaScript, the relationship between constructors and new commands is described in detail in this article, the concept and characteristics of the constructor, the principle and usage of the new command, and so on, if you are unfamiliar with the constructor, you can go and savor it. Here's a simple review.

A constructor is a function that provides a template for generating an object and describes the basic structure of the object. A constructor that can generate multiple objects, each with the same structure. In general, the constructor is the template of the object, which is an instance of the constructor.

The characteristics of a constructor are:

A: 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.

 function person () {
 this.name = ' Keith ';
} 
 var boy = new Person ();
Console.log (Boy.name); ' Keith '

2. Disadvantages of constructors

All instance objects can inherit the properties and methods in the constructor. However, properties cannot be shared between instances of the same object.

 function Person (name,height) {
 this.name=name;
 This.height=height;
 This.hobby=function () {return
 ' watching movies ';
}
 } 
var boy=new person (' Keith ', 180);
 var girl=new person (' rascal ', 153); 
 Console.log (Boy.name); ' Keith '
 Console.log (girl.name);///' Rascal '
 Console.log (boy.hobby===girl.hobby);//false

In the code above, a constructor person generates two object instances boy and girl, and has two properties and one method. However, their hobby methods are not the same. That is, whenever you use new to call a constructor to put back an object instance, a hobby method is created. This is neither necessary nor wasteful, since all hobby methods are faces and can be shared by two object instances.

Therefore, the disadvantage of a constructor is that a property or method cannot be shared between object instances of the same constructor.

The role of 3.prototype properties

To resolve the disadvantage of not sharing properties between object instances of a 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 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 the constructor, the object instance's prototype is pointed to the prototype property of the constructor. Each constructor has a prototype attribute, which is the prototype object of an object instance.

 function Person (name,height) {
 this.name=name;
 this.height=height;
 } 
 Person.prototype.hobby=function () {return
 ' watching movies ';
 }
 var boy=new person (' Keith ', 180);
 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 code above, if you put the hobby method 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 a constructor, and for an object instance, prototype is a prototype object for an object instance. So prototype is both an attribute and an object.

The properties of a prototype object are not properties of an object instance. The properties of an object instance are inherited from a constructor-defined property because there is a this keyword inside the constructor that points to the object instance that will be generated. The properties of an object instance are actually those defined within the constructor. As long as you modify the properties and methods on the prototype object, the changes are immediately reflected on all object instances.

 Person.prototype.hobby=function () {return
 ' swimming ';
 }
 Console.log (Boy.hobby===girl.hobby); True
 Console.log (Boy.hobby ());//' Swimming '
console.log (Girl.hobby ());//' Swimming '

In the code above, two object instances have changed since the hobby method of the prototype object was modified. This is because the object instance actually has no hobby method and is the hobby method of reading the prototype object. That is, when an object instance does not have the property and method, it goes to the prototype object to look up. If an instance object has a property or method of its own, it does not look on the prototype object.

Boy.hobby=function () {return
 ' play basketball ';
 }
 Console.log (Boy.hobby ()); ' Play basketball '
 Console.log (Girl.hobby ());//' Swimming '

In the code above, when the hobby method of a Boy object instance is modified, the hobby method on the prototype object is not inherited. However, girl still inherits the method of the prototype object.

To sum up:

A: The role of a prototype object is to define the properties and methods that are shared by all object instances.

B:prototype, which is a property for a constructor, is a prototype object for an object instance.

4. Prototype chain (prototype chains)

The object's properties and methods may be defined within itself, or it may be defined in its prototype object. Since the prototype object itself is also an object for an object instance, it has its own prototype, so it forms a prototype chain (prototype chain). For example, a object is a prototype of a B object, a B object is a prototype of a C object, and so on. All of the objects at the top of the prototype are Object.prototype, that is, the object that the prototype attribute of the object constructor points to.

Of course, the Object.prototype object also has its own prototype object, which is a null object without any attributes and methods, and the null object does not have its own prototype.

1 Console.log (object.getprototypeof (Object.prototype)); Null

2 Console.log (Person.prototype.isPrototypeOf (boy))//true

  The characteristics of the prototype chain (prototype chain) are:

A: When reading a property of an object, the JavaScript engine first looks for the object's properties, and if it can't find it, go to its prototype and find it, if you can't find it, to the prototype. Returns undefined if the object.prototype is still not found at the top level.

B: If the object itself and its prototype define a property of the same name, then the object's own properties are read preferentially, which is called "overiding".

C: A level up in the prototype chain looking for a property, has an impact on performance. The higher the properties of the prototype object, the greater the impact on performance. If you look for a property that does not exist, the entire prototype chain is traversed.

Look at the concept may be more obscure, let's take a look at an example. But it's really important to understand the concept.

 var arr=[1,2,3]; 
Console.log (arr.length); 3
Console.log (arr.valueof ())//[1,2,3]
console.log (arr.join (' | '))//1|2|3

In the code above, an array arr is set, with three elements inside the array. We didn't add any properties and methods to the array, but when we called Length,join (), valueof (), we didn't make an error.

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 and 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 Object.prototype. First, there is no valueof method for the ARR array, so the prototype object Array.prototype lookup. Then, you find that there is no valueof method on the Array.prototype object. Finally, and then to its prototype object Object.prototype lookup.

Let's look at the properties and methods of the Array.prototype object and the Object.prototype object respectively.

 Console.log (Object.getownpropertynames (array.prototype))
//["Length", "Tosource", "toString", "tolocalestring , "join", "reverse", "sort", "push", "pop", "Shift", "unshift", "splice", "concat", "slice", "LastIndexOf", "IndexOf", "F  Oreach "," Map "," filter "," reduce "," reduceright "," some "," every "," find "," FindIndex "," Copywithin "," Fill "," Entries ", "Keys", "Values", "includes", "constructor", "$set", "$remove"]
 console.log (Object.getownpropertynames ( Object.prototype)
 //["Tosource", "toString", "tolocalestring", "valueof", "Watch", "unwatch", "hasOwnProperty", "isPrototypeOf", "propertyisenumerable", "__definegetter__", "__definesetter__", "__lookupgetter__", "__ Lookupsetter__ "," __proto__ "," constructor "]

I believe, we see here, to prototype or indefinitely. This is normal, after all, JS is more important and more abstract concept, it is not possible to grasp so quickly, and then chew more than a few, perhaps grasp its essence. In some cases, there is a living example, which may also be a problem that we all encounter. You can look at the JS constructor and the prototype object.

5.constructor Properties

The prototype object has a constructor property, and the default point is to the constructor that contains the prototype object.

 function A () {};
 Console.log (a.prototype.constructor===a)//true

Note that prototype is the property of the constructor, and constructor is the object that the prototype property of the constructor points to, that is, the properties of the prototype object. Be careful not to confuse.

Console.log (A.hasownproperty (' prototype ')); True
 Console.log (A.prototype.hasownproperty (' constructor '));//true

Because the constructor property is defined above the prototype (prototype) object, it means that it can be inherited by all instance objects.

function A () {};
 var a=new a (); 
 Console.log (A.constructor); A ()
console.log (a.constructor===a.prototype.constructor);//true

In the code above, A is an instance object of constructor a, but a itself has no contructor property, which is actually read from the prototype chain.

A.prototype.constructor property.

The role of 5.1:constructor properties

A: Identify which constructor the prototype object belongs to

 function A () {};
 var a=new a (); 
 Console.log (a.constructor===a)//true
 console.log (a.constructor===array)//false

The code above indicates that using the constructor property, the constructor of instance object A is determined to be a, not an array.

B: Create another instance from the instance

 function A () {};
 var a = new A ();
var B = new A.constructor ();
Console.log (b instanceof A); True

In the code above, A is an instance object of constructor a, which can be called indirectly from A.constructor.

C: Calling its own constructor is possible

 A.prototype.hello = function () {return
 new This.constructor ();
 }

D: Provides a pattern that inherits another constructor from a constructor

 function Father () {} 
 function Son () {
Son.height.constructor.call (this);
 } 
 Son.height = new Father ();

In the code above, both father and son are constructors, and in the son, this increases the use of Father, which forms the son inheritance father effect.

E: Because the constructor attribute is a kind of prototype object and the relationship between the constructor, so in the modification of the prototype object, we must pay attention to the constructor point problem.

There are two solutions, either pointing the constructor property to the original constructor, or adding properties and methods to the prototype object to avoid instanceof distortion.

6.instanceof operator

The instanceof operator returns a Boolean value that indicates whether the specified object is an instance of a constructor.

 function A () {};
var a = new A ();
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 multiple constructors.

 function A () {};
 var a = new A (); 
Console.log (a instanceof a); True
Console.log (a instanceof Object);//true

Note that the Instanceof object can be used only for complex data types (arrays, objects, and so on) and not for simple data types (Boolean, numeric, string, and so on).

 var x = [1];
 var o = {};
 var B = true;
 var c = ' string ';
 Console.log (x instanceof Array); True
console.log (o instanceof Object);//true
 Console.log (b instanceof Boolean);//false
Console.log (c Instanceof String); False

Also, null and undefined are not objects, so instanceof always returns false.

Console.log (null instanceof Object); False Console.log (undefined instanceof Object); False

With the instanceof operator, you can also skillfully resolve the problem of adding the new command when calling the constructor.

 Function Keith (name,height) {
 if (! This instanceof Keith) {return
 new Keith (Name,height);
 }
 this.name = name;
 this.height = height;
}

In the code above, the instanceof operator is used to determine whether the this keyword in the function's body points to an instance of the constructor Keith, and if not, it means forgetting to add the new command, at which point the constructor returns an object instance to avoid unexpected results.

Due to the reasons for space, temporarily 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.

The above is a small set to introduce the details of JavaScript prototype attributes (recommended) related knowledge, I hope to help.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.