JS prototype inheritance and class inheritance

Source: Internet
Author: User

Class-Inheritance (constructors)

JS In fact there is no class concept, the so-called class is also simulated. Especially when we use the New keyword, it makes the concept of "class" more like classes in other languages. Class inheritance invokes the constructor of the parent class within a function object, making itself available to the parent class's methods and properties. The call and apply methods provide support for class-type inheritance. By changing the context of this, the subclass itself has various properties of the parent class.

JavaScript<textarea class="crayon-plain print-no" style="font-size: 13px !important; line-height: 15px !important; z-index: 0; opacity: 0" readonly="" data-settings="dblclick">var father = function () {this.age = 52; This.say = function () {alert (' Hello i am ' + this.name ' and I am ' +this.age + ' years old '); }}var child = function () {this.name = ' bill '; Father.call (this);} var man = new Child (); Man.say ();</textarea>
1234567891011121314151617181920212223 var father = function() { This . Age = ; This . Say = function() { alert(' Hello i am '+ this . Name ' and I am '+this. Age + ' years old ');   }} var child = function() { This . Name = ' bill '; father. Call(this); }var man = new child (); man. Say();

Prototype inheritance

Prototype inheritance is often used in development. It differs from class inheritance because inheritance is not on the object itself, but on the object's prototype (prototype). Each object has a prototype, which in the browser is represented by a hidden __proto__ attribute. In some modern browsers you can change them. For example, in Zepto, it is by adding the Zepto FN object to the __proto__ property of an empty array, so that the array becomes a Zepto object and has all the methods. Again, when an object needs to call a method, it goes back to the nearest prototype and finds the method, and if it does not, it continues to look down again. This step-by-step search, has been found to find the method. The prototypes of these lookups form the prototype chain of the object. The final point of the prototype is null. The prototype inheritance we are talking about is the prototype of the parent-to-child approach to the subclass. These methods and properties are not owned in the constructor of the subclass.

JavaScript<textarea class="crayon-plain print-no" style="font-size: 13px !important; line-height: 15px !important; z-index: 0; opacity: 0" readonly="" data-settings="dblclick">var father = function () {}father.prototype.a = function () {}var child = function () {}//start inheriting child.prototype = new father (); var man = new Child (); Man.a ()</textarea> ;
1234567891011121314151617 var father = function() { }father. Prototype. A = function() { } var child = function(){} //Start inheritingchild. Prototype = new Father(); var man = new child (); man. A();

You can see that the seventh line implements the prototype inheritance. Many people are not unfamiliar with this way. By printing the man in the browser, we can see the inheritance of the individual prototypes.

You can see the hierarchical relationship Child->object (Father instantiated objects)->father. Child is inheriting something from the Father prototype through the middle layer. But why is there a layer of object in the middle, why not put child.prototype = Father.prototype. The answer is that if you do this, there is no difference between child and father. You should remember that there is a constructor attribute in prototype that points to a constructor. In normal circumstances we will change the value of constructor back to the constructor that points to child. But if Father.prototype is assigned to Child.prototype, then who should constructor point to? So it is clear that only the middle layer can be used to keep child and father as separate objects.

Contrast

In contrast to prototypes, what is different about constructor (class) inheritance? First of all, the method inherited by the constructor will exist in the parent object, and each time the instance is stored back in memory, the practice of Funciton is not expected to cause any performance problems. Second, the class-type inheritance is immutable. At run time, it is not possible to modify or add new methods, which is a way of dying out. The prototype inheritance can be modified by altering the prototype link and the child class. In addition, class inheritance does not support multiple inheritance, but for prototype inheritance, you only need to write extend to extend the object.

Combination mode

Another pattern is the inheritance of the parent class in combination with the respective merits of class inheritance and prototype inheritance. Inherits a property with a class, and the prototype inherits the method. This pattern avoids the common nature of attributes, because in general, the properties of each subclass are private and the methods are unified. This pattern is called a combinatorial pattern and is a common method of inheriting classes.

JavaScript<textarea class="crayon-plain print-no" style="font-size: 13px !important; line-height: 15px !important; z-index: 0; opacity: 0" readonly="" data-settings="dblclick">function Father () {this.a = ' father '}father.prototype.b = function () {alert (THIS.A)}var child = function () {f Ather.call (this)}child.prototype = new father ();</textarea>
12345678910111213141516171819 function father() { This . A = ' father ' }father. Prototype. b = function() { Alert(this. A) }var child = function() { father. Call(this) }child. Prototype = new Father();

New keyword and obeject.create method

In the article, bloggers point out the drawbacks of using the new keyword. "The New keyword masks the true stereotype inheritance in JavaScript, making it more like class-based inheritance," he says. In fact, the new keyword is just a residue left by JavaScript in order to gain popularity by adding a grammar period similar to Java. " The author recommends that we use the Object.create method to create or instantiate an object. Dew has been tested, using new and using the Object.create method is to add objects to the prototype. We can look at the code:

JavaScript<textarea class="crayon-plain print-no" style="font-size: 13px !important; line-height: 15px !important; z-index: 0; opacity: 0" readonly="" data-settings="dblclick">var father = function () {THIS.A = ' father '}father.prototype.b = function () {alert (THIS.A)}var obj = new father () ;</textarea>
123456789 var father = function() { This . A = ' father ' } father. Prototype. b = function() {alert(this). A)} var obj = new Father();

To print obj in the browser, you can observe its structure. It is an object, has its own properties, and also has a B method in its __proto__ familiarity. In the back of the __proto__ there are father, you can see that the prototype is from the father.

So Objcet.create method, we can also test it by the following code:

JavaScript<textarea class="crayon-plain print-no" style="font-size: 13px !important; line-height: 15px !important; z-index: 0; opacity: 0" readonly="" data-settings="dblclick">var father = {A: ' Father ', B:function () {alert (THIS.A); }}var obj = object.create (father); Console.dir (obj)</textarea>
123456789101112131415 var father = { a: ' father ', b: function() { Alert(this. a);    }}var obj = Object. Create(father); console. Dir(obj)

The following is the result of the browser output:

As you can see, the object constructed with the Create method, the A attribute and the B method are all on the object's prototype, that is, we can change the method and property on the prototype of obj dynamically by changing the properties of the father, and the above is not changed by the instance generated by the constructor function with the new keyword. From here, we can also see some differences between class inheritance and prototype basics.

Conclusion

Prototype inheritance is more consistent with the characteristics of JS language. Because it is a part of JS's powerful prototype. And the class inheritance, instead of calling it inheritance, is rather a function of the use of techniques to simulate inheritance.

JS prototype inheritance and class inheritance

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.