Deep understanding of the differences between constructors and prototype objects in JavaScript

Source: Internet
Author: User
Tags instance method object object

A detailed description of the prototype property in JavaScript This article details the disadvantages of the constructor and the prototype (prototype), the prototype chain (prototype chain), the constructor (constructor), Some features of the instanceof operator. If you are unfamiliar with prototype and constructors, you can go to JavaScript with the prototype attribute in detail and JavaScript in the close relationship between the constructor and the new command. Taste carefully. Let's start with a simple review.

 First , we know that constructors are templates that generate objects, and one constructor can generate multiple objects, each with the same structure. The disadvantage of the constructor is that whenever you instantiate two objects, you need to call one of the two constructor's methods, and the disadvantage is that it takes up memory and is not necessary.

  secondly , in order to solve the problem that the properties and methods of the constructor cannot be shared by the object instances, we can put the properties and methods that need to be shared on the prototype (prototype) object. All properties and methods on the prototype object are shared by the object instance. For constructors, prototype is a property of a constructor, and for an object instance, prototype is the prototype object of an object instance. So prototype is a property and an object.

  then , in addition to undefined and null, each data type can be considered an object, and each object has its own prototype. The top of all the prototypes of all objects is Object.prototype, which 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 properties and methods, and the null object does not have its own prototype.

The characteristics of the prototype chain are:

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.

  again , the constructor property is a property on the prototype object that can be shared by all instance objects. Note that prototype 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. Since the constructor property is a prototype object and a constructor relationship, it is important to pay attention to the point of constructor when modifying the prototype object.

  finally , the instanceof operator returns a Boolean value that determines whether the object is an instance of a constructor.

In the next share, we talk about some methods of object and some methods of Object.prototoype. Although all are conceptual issues, understanding these concepts can be very helpful for the understanding of the MVVM framework and the various JS frameworks.

The following sharing will be divided into the following sections:

The difference between 1.Object and Object.prototype

2.object.getprototypeof ()

3.object.setprototypeof ()

4.object.create ()

5.object.prototype.isprototypeof ()

6.object.prototype.__proto__

The difference between 1.Object and Object.prototype

  Personally, one of the ways to learn JavaScript is to understand every ". What does it mean, the properties and methods that call itself, or the properties and methods of the object inheriting the prototype. Look at the properties and methods of the object constructor and the prototype of the constructor Object.prototype.

Object is a constructor, and Object.prototype is a prototype object of a constructor function. the properties and methods of the constructor itself cannot be shared, and the properties and methods of the prototype object can be shared by all instance objects.

Properties and methods of object:

Properties and methods of Object.prototype:

In the example above, object has its own method prototype,getprototypeof (), setprototypeof (), etc., and these methods cannot be shared by the instance. Properties and methods such as hasownproperty,isprototypeof (), constructor, and object.prototypeof () can be shared by instance objects. Give me one of the simplest examples.

1     function Keith () {}2     var a = new Keith (); 3     console.log (a.prototype);    Undefined4     Console.log (a.constructor);    Keith ()

In the above code, the constructor Keith does not have any properties and methods. Undefined is returned when accessing the prototype property because the prototype property has no way to inherit from the constructor and can only be accessed by the constructor itself. Constructor returns Keith () because the constructor property itself is a property in Object.prototype and can be shared by all instance objects.

So the question is, how do you know the prototype of the instance object? This can be achieved through the Object.isprototypeof method and the isPrototypeOf method that inherits the prototype object.

1     console.log (Keith.prototype.isPrototypeOf (a));    True2     Console.log (object.getprototypeof (a) = = = Keith.prototype)//true

In the above code, the prototype of instance object A is Keith.prototype. These two properties are described later.

2.object.getprototypeof ()

  Object.getPrototypeOfmethod returns the prototype of an object. This is the standard way to get a prototype object.

1     //null object prototype is Object.prototype 2     console.log (object.getprototypeof ({}) = = = Object.prototype)//True 3      4     //Prototype Function.prototype 5 function     Keith () {} 6     Console.log (object.getprototypeof (keith) = = = = Function.prototype)     //true 7  8     //array of prototypes Array.prototype 9     var arr = [1,2,3];10     console.log ( Object.getprototypeof (arr) = = = Array.prototype)///true

  

3.object.setprototypeof ()

  The Object.setprototypeof method can set a prototype for an existing object and then return a new object. This can receive two parameters, the first one is an existing object, and the second is a prototype object.

1     var keith = {2         height:180 3     }; 4     var rascal = object.setprototypeof ({}, Keith); 5     Console.log (RASC Al.height);    6  7     //Up to two code snippets are the same. 8     var keith = {9         height:18010     };11     var rascal ={12         __proto__: keith13     };14     Console.log (rascal.height);    180

In the above code, the Rascal object is Object.setPrototypeOf a new object returned by the method. The object itself is empty, and the prototype is a Keith object, so the Rascal object can get all the properties and methods of the Keith object. The Rascal object itself does not have a height property, but the JavaScript engine finds its prototype object, Keith, and then reads the height property of Keith.

4.object.create ()

  The Object.create method is used to generate a new instance of an object from a prototype object, which can be substituted by the new command. It takes an argument, which is the prototype object to inherit, and then returns an instance object.

1     var Keith = {2         hobby:function () {3             return ' watching Movies '; 4         }5     };6 7     var rascal = Object.cre Ate (Keith); 8     Console.log (Rascal.hobby ())    //' watching Movies '

In the above code, the Object.create method takes the Keith object as a prototype object for Rascal, at which point Rascal inherits all the properties and methods in the Keith object. Rascal becomes an instance object of the Keith object. The following code is a good understanding.

1     function Keith () {};2     Keith.prototype.hobby = function () {3         return ' watching Movies '; 4     }5 6     var rascal = object.create (Keith), 7     Console.log (Rascal.hobby ())    //' watching Movies ';

Both the new operator and the Object.create method return an object instance, but there are some differences.

1     function Keith () {}2     var a = new Keith (); 3     var b = object.create (Keith.prototype); 4 5     Console.log (a ins Tanceof Keith);    True6     Console.log (b instanceof Keith);    True

In the above code, you can use the new operator to call the constructor, return the object instance, and the argument passed by Object.create must be the prototype of the constructor, Keith.

In fact, if you have an older browser that does not support the Object.create method, you can use this code to construct a Object.create method.

1     if (typeof object.create!== ' function ') {2         object.create = function (x) {3             function F () {};4             F.prototype = x;5             return new F (); 6         };7     }

The following three ways of generating instance objects are equivalent.

1     var O1 = object.create ({}), 2     var O2 = Object.create (Object.prototype), 3     var O2 = new Object ();

When using the Object.create method, be aware that you must pass in the prototype object, or you will get an error.

1     var O1 = Object.create (); 2     Console.log (O1);//typeerror:object.create requires more than 0 arguments

The Object.create method generates an object instance that dynamically inherits the prototype object. In other words, modifying the properties and methods of the prototype object will be reflected on the object instance.

1     var keith = {2         height:1803     };4 5     var rascal = Object.create (Keith); 6     keith.height=153;7     Console.log (rascal.height)    //153

In the above code, modifying the prototype object will affect the resulting object instance.

The Object.create method generates an object that inherits the constructor of its prototype object.

1     function Keith () {};2     var boy = new Keith (), 3     var girl = object.create (boy); 4     Console.log ( Object.getprototypeof (girl) = = = Boy); True5     console.log (girl.constructor = = = Keith);    True6     console.log (girl instanceof Keith);    True

In the above code, the prototype of the girl object is the boy object, and the constructor property of the girl object points to the constructor of the prototype object, Keith.

5.object.prototype.isprototypeof ()

  An isprototypeof method of an object instance that determines whether an object object is a prototype of another object.

1     var O1 = {};2     var O2 = object.create (O1); 3     var O3 = object.create (O2); 4 5     Console.log (o1.isprototypeof (O2)); True6     Console.log (o2.isprototypeof (O3));//true7     Console.log (o1.isprototypeof (O3));//true

As you can see in the code above, ISPROTOTYPEOF returns true as long as an object is on the prototype chain.

1     function Keith () {};2 3     console.log (Function.prototype.isPrototypeOf (Keith));    True4     Console.log (Object.prototype.isPrototypeOf (Function));    True5     Console.log (object.getprototypeof (object.prototype) = = = null);//true

In the above code, the constructor Keith's prototype points to Function.prototype, while the constructor function's prototype points to Object.prototype. The prototype of object points to a null object without any properties and methods.

6.object.prototype.__proto__

The __proto__ Property (front and back two underline) can overwrite an object's prototype object. This belongs to the instance method.

1     var keith = {};2     var rascal = {};3     rascal.__proto__ = keith;4     console.log (keith.isprototypeof (Rascal ));    True

In the above code, Rascal's prototype is pointed to the Keith object through the __proto__ property of the Rascal object.

  __proto__Property only the browser needs to deploy, the other environment can not have this attribute, and the front and back of the two underscore, that it is essentially an internal property, should not be exposed to the user. Therefore, you should use this attribute sparingly, but use Object.getPrototypeof() (read) and Object.setPrototypeOf() (set) to read and write the prototype object.

To make a small summary, the above to some of the properties and methods of introduction can be summed up in one sentence:

  The properties of the constructor itself cannot be shared by the object instance, and the properties and methods on the prototype object can be shared by the object instance being used.

Finish.

Deep understanding of the differences between constructors and prototype objects in JavaScript

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.