Learning notes on JavaScript inheritance [For Beginners] _ javascript skills

Source: Internet
Author: User
The following small series will bring you a study note on JavaScript inheritance. I think it is quite good. Now I will share it with you and give you a reference to JavaScript as an object-oriented language (JS is object-based), which is essential for inheritance, however, because there is no concept of a class, it is not like the real object-oriented programming language that implements inheritance by class, but it can be inherited by other methods. There are many methods to implement inheritance. Below are just a few of them.

1. prototype chain inheritance

Function Person () {// The inherited function is called a super-type (parent class, base class) this. name = 'mumu'; this. age = '18';} Person. prototype. name = 'susu'; // when the attribute name is the same as the proximity principle, you need to first find it in the instance, and then find function Worker () in the prototype () {// The inherited function is called the subtype (subclass, derived class) this. job = 'student ';} Worker. prototype = new Person (); // inherits from the prototype chain. The object instance after super-type instantiation is assigned to the prototype property var p2 = new Worker (); console. log (p2.name); console. log (p2 instanceof Object); // All constructors of ture inherit from Object

The key to inheritance is: Worker. prototype = new Person (); prototype of Worker into an instance of Person and inherit from the prototype chain.

Note: When prototype chain is used to implement inheritance, you cannot use the object literal to create the prototype method, because this will interrupt the relationship and rewrite the prototype chain.

Prototype chain inheritance:

1. If there is a reference sharing problem, they still share a space, and subclass will affect the parent class.

function Person() {        this.bodys=['eye','foot'];    }        function Worker(){     }    Worker.prototype=new Person();    var p1=new Worker();    p1.bodys.push('hand');    var p2=new Worker();     console.log(p1.bodys);    console.log(p2.bodys);

2. When creating a child-type instance, parameters cannot be passed in a super-Type constructor.

So how can we solve the two problems of prototype chain? Let's continue to look at the Inheritance Method below ~

Ii. Borrow constructor inheritance (also called object impersonate, counterfeit object or classic inheritance)

Function Person (name, age) {this. name = name; this. age = age; this. bodys = ['eye ', 'foot'];} Person. prototype. showName = function () {console. log (this. name);} function Worker (name, age, job) {Person. call (this, name, age); this. job = job; // Add attributes to subclass} var p1 = new Worker ('mumu', '18', 'studen'); p1.bodys. push ('hand'); var p2 = new Worker (); console. log (p1.name); console. log (p2.bodys); console. log (p1.showName ());

Simple Analysis of the above principle of using borrow constructor: Person. call (this, name, age); this code calls the parent constructor, inherits the parent attribute, and uses the call method to call the Person constructor to change this during function execution, here this-> A new Worker object constructor disguise method: Pass the Worker to the Person above.

When the reference type is placed in the constructor, it will not be shared, so p2 will not be affected.

Here, the constructor inheritance method solves the problem that the prototype chain cannot pass parameters and the reference type is shared.

TIPS: The call () and apply () methods can change the function execution scope. In short, they can change the content that this points to in the function.

Both call () and apply () accept two parameters: the first is the scope of the function to be run, and the other is the passed parameter.

The difference between call and apply is that the parameters are different.
Parameters in the call must be enumerated one by one.
The parameters in apply must be arrays or arguments objects.

So the question is: why is the p1.showName () Result incorrect? ---- Borrow the constructor Inheritance Method to inherit only the attributes and methods in the constructor. Here we also find a problem with borrowing constructors.

Note: Because we put all the methods in the constructor, every time we instantiate them, we will allocate memory space to it, which will waste resources. Therefore, we usually put the methods in the prototype, attribute is placed in the constructor.


Inheritance of borrow constructors:

Because the borrow constructor can only inherit the attributes and methods in the constructor, the methods defined in the super-type prototype are invisible to the subclass, so it is equivalent to having no prototype. Result All methods can only be defined in the constructor, so no function is reused.

So how can we solve the problems arising from borrow Constructors? It depends on the following inheritance method.

Iii. Combined inheritance (pseudo-classic inheritance)

Function Person (name, age) {this. name = name; this. age = age;} Person. prototype. showName = function () {console. log (this. name);} function Worker (name, age, job) {Person. call (this, name, age); // borrow the constructor this. job = job;} Worker. prototype = new Person (); // prototype chain inherits var p1 = new Worker ('mumu', '18', 'studen'); console. log (p1.age); p1.showName ();

Combined inheritance: combines the prototype chain with the borrow constructor.

Idea: Use the prototype chain to inherit the attributes and methods of the prototype, and use the constructor to inherit the attributes of the instance.

In the above example, Person. call (this, name, age); borrow the constructor to inherit the attributes

Worker. prototype = new Person (); prototype chain inherits the methods, avoids the disadvantages of both, integrates their advantages, and becomes the most common inheritance mode.

Combination inheritance:

Two super-Type constructor calls, one being within the sub-Type constructor when the sub-type prototype is created.

To solve this problem, we need to use the parasitic combined inheritance method.

Iv. Original Type inheritance

function object(proto) {    function F() {}    F.prototype = proto;    return new F();  }  var person = {    name: 'mumu',    friends: ['xiaxia', 'susu']  };  var anotherPerson = object(person);  anotherPerson.friends.push('wen');  var yetAnotherPerson = object(person);  anotherPerson.friends.push('tian');  console.log(person.friends);//["xiaxia", "susu", "wen", "tian"]console.log(anotherPerson.__proto__)//Object {name: "mumu", friends: Array[4]}

In a simple analysis, function object (proto) is a temporary transit function. The proto parameter in it indicates an object to be passed in. The F () constructor is a newly created object, used to store passed objects. prototype = proto; assign an object instance to the prototype object of the F constructor, and return the object instance of the passed object. The original type inheritance still shares the attributes of the reference type.

5. Parasitic inheritance

// Temporary transit function object (proto) {function F () {} F. prototype = proto; return new F () ;}// parasitic function create (proto) {var f = object (proto); f. love = function () {return this. name;} return f;} var person = {name: 'mumu', friends: ['xiaxia ', 'susu']}; var anotherPerson = create (person); console. log (anotherPerson. love (); parasitic combined inheritance

6. Parasitic combined inheritance

Function object (proto) {function F () {} F. prototype = proto; return new F ();} // parasitic function create (Person, Worker) {var f = object (Person. prototype); // create the object f. constructor = Worker; // adjust the prototype construction pointer to enhance the Worker object. prototype = f; // specify the object} function Person (name, age) {this. name = name; this. age = age;} Person. prototype. showName = function () {console. log (this. name);} function Worker (name, age, job) {Person. call (this, name, age); this. job = job;} create (Person, Worker); // parasitic combination inheritance var p1 = new Person ('mumu', '18', 'studen'); p1.showName ();

This method is also the most perfect and ideal method to implement inheritance.

The above JavaScript inheritance Study Notes [beginner's note] are all the content shared by Alibaba Cloud xiaobian. I hope you can give us a reference and support for your feet.

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.