JavaScript inheritance (1)

Source: Internet
Author: User

Object-oriented and Object-based

Almost every developer has development experience in object-oriented languages (such as C ++, C #, and Java. In traditional object-oriented languages, there are two very important concepts: classes and instances. Class defines the common behaviors and methods of a class of things, while the instance is a specific implementation of the class. We also know that object-oriented programming has three important concepts: encapsulation, inheritance, and polymorphism.

However, in the JavaScript world, all of these features do not seem to exist. JavaScript is not an object-oriented language, but an object-based language. There are some interesting features, such as the fact that everything in JavaScript is an object, including strings, arrays, dates, numbers, and even functions. For example:

// Define a function-add
Function add (a, B ){
Add. invokeTimes ++;
Return a + B;
}
// Because the function itself is also an object, an attribute is defined for function add to record the number of times this function is called.
Add. invokeTimes = 0;

Add (1 + 1 );
Add (2 + 3 );
Console. log (add. invokeTimes); // 2

 

Simulate classes and inheritance in JavaScript

In the object-oriented language, we use classes to create a custom object. However, everything in JavaScript is an object,So how can I create a custom object?

This requires the introduction of another concept-prototype. We can simply regard prototype as a template, and all newly created custom objects are prototype) A copy of (in fact, it is not a copy but a link, but this link is invisible, giving people the feeling that it is a copy ).

Let's take a look at an example of creating a custom object through prototype:

// Constructor
Function Person (name, sex ){
This. name = name;
This. sex = sex;
}
// Define the prototype of Person. attributes in the prototype can be referenced by custom objects.
Person. prototype = {
GetName: function (){
Return this. name;
},
GetSex: function (){
Return this. sex;
}
}

Here we call the Person function a constructor, that is, a function that creates a user-defined object. It can be seen that JavaScript simulates the class function through constructor and prototype.
Code for creating a custom object (instantiation class:

    var zhang = new Person("ZhangSan", "man");
console.log(zhang.getName()); // "ZhangSan"

var chun = new Person("ChunHua", "woman");
console.log(chun.getName()); // "ChunHua"

When the code var zhang = new Person ("ZhangSan", "man") is executed, the following items are actually done internally:

  • Create a blank Object (new Object ()).
  • Copy the attributes (key-value pairs) in Person. prototype to this empty object (as we mentioned earlier, the internal implementation is not a copy but a hidden link ).
  • Pass this object to the constructor using the this keyword and execute the constructor.
  • Assign this object to the variable zhang.

 

To prove that the prototype template is not copied to an instantiated object, it is a link method. See the following code:

Function Person (name, sex ){
This. name = name;
This. sex = sex;
}
Person. prototype. age = 20;

Var zhang = new Person ("ZhangSan", "man ");
Console. log (zhang. age); // 20
// Overwrite the age attribute in prototype
Zhang. age = 19;
Console. log (zhang. age); // 19
Delete zhang. age;
// After deleting the instance Property age, the property value is obtained from prototype.
Console. log (zhang. age); // 20

This hidden prototype link implemented inside JavaScript is the gentle soil on which JavaScript depends, and is also the basis for simulating inheritance.

 

How to implement simple inheritance in JavaScript?
The following example creates an Employee class, which inherits all attributes in prototype from Person.

Function Employee (name, sex, employeeID ){
This. name = name;
This. sex = sex;
This. employeeID = employeeID;
}
// Point the prototype of Employee to an instance of Person
// Because the Person instance can call the method in the Person prototype, the Employee instance can also call all attributes in the Person prototype.
Employee. prototype = new Person ();
Employee. prototype. getEmployeeID = function (){
Return this. employeeID;
};

Var zhang = new Employee ("ZhangSan", "man", "1234 ");
Console. log (zhang. getName (); // "ZhangSan

 

The inheritance implementation above is rough and has many problems:

  • It is not appropriate to instantiate the Person when creating the Employee constructor and prototype (hereinafter referred to as the class.
  • The constructor of the Employee class cannot call the constructor of the parent class Person, causing repeated value assignment to the name and sex attributes in the Employee constructor.
  • The functions in Employee override the functions with the same name in Person, and there is no overload mechanism (which is a type problem with the previous one ).
  • The syntax for creating JavaScript classes is too fragmented and not as elegant as that in C #/Java.
  • The constructor attribute is incorrect. This will be discussed in the second article.

We will complete this example in Chapter 3.

 

Implementation of JavaScript inheritance

Because JavaScript itself does not have a complete implementation of classes and inheritance, and we also see that there are many problems through manual implementation, there are already many implementations for this challenging task online:

  • Douglas Crockford-Prototypal Inheritance in JavaScript
  • Douglas Crockford-Classical Inheritance in JavaScript
  • John Resig-Simple JavaScript Inheritance
  • Dean Edwards-A Base Class for JavaScript Inheritance
  • Prototype
  • Mootools
  • Extjs

This series of articles will analyze these implementations one by one to gain a deep understanding of how to implement classes and inheritance in JavaScript.

In the next chapter, we will introduce relevant knowledge in class implementation, such as this, constructor, prototype, and so on.

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.