How does JavaScript implement inheritance

  • 2020-03-30 00:53:25
  • OfStack

Recently, I read the experience of a person's interview on taobao on the Internet, and then I found that I had a lot of unclear places. Therefore, I hereby write some articles to deepen my understanding of some issues.

One question mentioned in the article is: how does JavaScript implement inheritance?

Below, I will elaborate on some methods and examples found on the Internet to explain, in order to deepen their own impression.

We know that function in JavaScript is versatile, and can be used for class definitions as well as function definitions.

JavaScript inheritance, too, is a bit odd to say. Unlike C++ and some object-oriented languages, it has no access-control modifiers such as public and private, and no implement or other specific notation to indicate implementation inheritance.

Refer to the following example for inheritance of javascript classes.


<script type="text/javascript"> 
function Person() {
    //  attribute  
    this.Gender = "female";
    this.Age = 18;
    this.Words = "Silence";
    //  methods 
    this.shouting = function() {
        alert(" Happy oh! Method of the parent class ");
    }
}
//  inheritance 
function Programmer() {
    this.base = Person;
}
Programmer.prototype = new Person;
//Add a new method to the subclass
Programmer.prototype.typeCode = function() {
    alert(" The an is knock code of! IT Migrant workers, very unhappy. Subclass method ");
}
//Invoke the sample
function sayHello() {
    var a = new Programmer();
    alert(a.Gender); //Invokes the properties of the parent class
    a.shouting(); //Calls a method of the parent class
    a.typeCode(); //Calls methods of subclasses
}        
sayHello();
</script>

On the case, the first is to declare a person class, contains some of the attributes and methods, and then went on to declare a programmer, one of the base attribute, this property is not required, but out of specification, and later in finding objects inherited classes all need to write, and then is to give the programmer a prototype object (prototype) to copy the person class; Class inheritance is then implemented.

Simulate some of the principles of classes and inheritance in JavaScript

In object-oriented languages, we use classes to create a custom object. Whereas everything in JavaScript is an object, how do you create a custom object?

We can simply think of prototype as a template, and any new custom object created is a copy of that template (it's actually not a copy but a link, but the link is invisible, so it feels like a copy).

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


//The constructor
  function Person(name, sex) {
      this.name = name;
      this.sex = sex;
  }
  //Define a prototype of a Person whose properties can be referenced by a custom object
  Person.prototype = {
      getName: function() {
          return this.name;
      },
      getSex: function() {
          return this.sex;
      }
  }

Here we call the function Person a constructor, which is the function that creates the custom object. As you can see, JavaScript simulates the implementation of the class through constructors and prototypes.

Here is an example to illustrate the specific work javascript does to create a custom object:


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") executes, it actually does the following internally:

Create a blank Object(new Object()).
Copy the properties (key-value pairs) from person.prototype into the empty object (we mentioned earlier that the internal implementation is not a copy but a hidden link).
Pass the object through this keyword to the constructor and execute the constructor.
Assign this object to the variable zhang.
All work done.
To prove that the prototype template is not copied into the instantiated object, but is a link, 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
//Override the age property in prototype
zhang.age = 19;
console.log(zhang.age); // 19
delete zhang.age;
//After the instance property age is removed, the property value is retrieved from prototype
console.log(zhang.age); // 20

In this case, if he is just by copying, and is deleted after this age the attributes, this object will not exist, but the age of the case attributes can also output, or to cover the previous value, we just delete the subclasses of the same name attribute, and the age of the parent class attribute by a kind of invisible link still exist in the object.

How to implement simple inheritance in JavaScript?

The following example creates an Employee class, Employee, which inherits all the attributes from the prototype 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 instances of Person can invoke methods in the Person stereotype, instances of Employee can also invoke all attributes in the Person stereotype.
Employee.prototype = new Person();
Employee.prototype.getEmployeeID = function() {
    return this.employeeID;
};
var zhang = new Employee("ZhangSan", "man", "1234");
console.log(zhang.getName()); // "ZhangSan

Okay, so that's just some details about how javascript implements inheritance, and how to implement inheritance.

To summarize, the inheritance mechanism in javascript is only simulated, which is rough and flawed for some object-oriented languages, but in general, it should not discourage front-end developers.


Related articles: