Comparison of several inheritance methods in Javascript and several inheritance methods in javascript

Source: Internet
Author: User

Comparison of several inheritance methods in Javascript and several inheritance methods in javascript
Opening

In the 'strict' sense, javascript is not a real object-oriented language. The reason for this is that javascript, as a weak language, is very different from the inheritance method of a strong language like java or c, by default, it is a non-mainstream object-oriented method, and many books have even described it as a non-fully object-oriented language. In fact, I personally think that what method is not important. What is important is whether we have the idea of object-oriented. javascript is not an object-oriented language and may not be studied in depth, this article is specially written for communication.

Why inheritance using javascript

The performance of early pc machines was not flattering. All the pressure was on the server side, and the client browser was purely a decoration. In addition, the popular table layout at that time and the Internet access through telephone lines led to a very powerful card for browsing a webpage. Today, the rapid development of the Internet era has greatly improved the personal computer hardware, the client browser is also very sour in performance, and the web development model is also quietly changing: the server is no longer as "hard" as before ", instead, let the browser handle more tasks as much as possible. As a result, the pressure is distributed to each client, which not only saves the cost, as a result, web Front-end development becomes more interesting-more and more front-end frameworks are emerging, and many front-end MVC frameworks are even emerging. In this context, the role of javascript is definitely not only for some simple verification, send some requests or operate some DOM, more need to assume a role similar to the front-end routing and service layer, in addition, javascript requires a lot of logic tasks, including the extraction of front-end data (that is, model). Only by using object-oriented thinking can we process the extraction data well, therefore, inheritance plays an important role here.

Starting with a simple requirement

Now, a model named "Person" is extracted from the front-end, which has the basic attribute name and age. By default, everyone can talk. Therefore, the talking function "say" is placed on the prototype object for each instance to enjoy. For Man, it needs to inherit the basic attributes of Person and add its own unique attributes.

function Person (name, age) {    this.name = name;    this.age = age;}Person.prototype.say = function(){    console.log('hello, my name is ' + this.name);};function Man() {    //my own properties}
The following describes several mainstream inheritance methods. 1. prototype chain inheritance
function Person (name, age) {    this.name = name;    this.age = age;}Person.prototype.say = function(){    console.log('hello, my name is ' + this.name);};function Man() {}Man.prototype = new Person('pursue');var man1 = new Man();man1.say(); //hello, my name is pursuevar man2 = new Man();console.log(man1.say === man2.say);//trueconsole.log(man1.name === man2.name);//true

This inheritance method is very direct, in order to obtainPersonAll attribute methods (on the instance and on the prototype)new Person('pursue')The prototype assigned to the subclass. In fact, the subclass instanceman1,man2It is a completely empty object, and all attributes and methods must be searched through the prototype chain. Therefore, the attribute methods found are the same.
Therefore, it is unrealistic to directly use prototype chain inheritance.

2. Use constructor to inherit
function Person (name, age) {    this.name = name;    this.age = age;}Person.prototype.say = function(){    console.log('hello, my name is ' + this.name);};function Man(name, age) {    Person.apply(this, arguments);}//Man.prototype = new Person('pursue');var man1 = new Man('joe');var man2 = new Man('david');console.log(man1.name === man2.name);//falseman1.say(); //say is not a function

Here, the subclass uses apply to call the constructor of the parent class in the constructor to inherit the attributes of the parent class, which is much better than directly using the prototype chain, at least each instance has its own resource, but this method can only inherit the instance attributes of the parent class. Therefore, the say method cannot be found. In order to inherit all attributes and methods of the parent class, the prototype chain is modified to introduce the combination inheritance method.

3. Combined inheritance
function Person (name, age) {    this.name = name;    this.age = age;}Person.prototype.say = function(){    console.log('hello, my name is ' + this.name);};function Man(name, age) {    Person.apply(this, arguments);}Man.prototype = new Person();var man1 = new Man('joe');var man2 = new Man('david');console.log(man1.name === man2.name);//falseconsole.log(man1.say === man2.say);//trueman1.say(); //hello, my name is joe

Note thatMan1 and man2The instance property of overwrites the prototype property, but does not overwrite the prototype property.sayMethod (because they do not exist), so hereman1.say === man2.sayIf true is returned, you must be careful not to overwrite the prototype attribute because it is shared by all instances.

4. Parasitic combination inheritance

To be honest, I really don't know the name of this form below, but it is indeed the most popular and classic method of javascript inheritance. In fact, you only need to understand the structure of the prototype object:

function Person (name, age) {            this.name = name;            this.age = age;        }Person.prototype.say = function(){    console.log('hello, my name is ' + this.name);};function Man(name, age) {    Person.apply(this, arguments);}Man.prototype = Object.create(Person.prototype);//a.Man.prototype.constructor = Man;//b.var man1 = new Man('pursue');var man2 = new Man('joe');console.log(man1.say == man2.say);console.log(man1.name == man2.name);

In fact, the difference between parasitic combination inheritance and the above combination inheritance lies only in the method of constructing the subclass prototype object (A. and B.).Object.creat(obj)Method. This method performs a shortest copy on the input obj object, similar:

function create(obj){    function T(){};    T.prototype = obj;    return new T();}

Therefore,a.The prototype object of the subclass is connected to the prototype object of the parent class, instead of copying the prototype of the subclass directly like the typical combination inheritance (for exampleMan.prototype = new Person();) To overwrite the attributes. The parasitic combination Inheritance Method inherits the instance attributes and prototype attributes respectively, making the implementation more reasonable.

Note:Code B does not change the results of instanceof, but it is more rigorous for scenarios that require construcor.

Synchronization of simplified books
Blog sync

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.