Understanding of JavaScript classes, prototype chains, inheritance

Source: Internet
Author: User

I. Preamble

?? Unlike other object-oriented languages, such as Java, the JavaScript language does not have a standard definition of the implementation and inheritance of the class, but instead gives it to programmers, giving programmers more flexibility (and, of course, more headaches) to define classes and implement inheritance. (The following does not discuss the use of class, extends keywords in ES6 to implement classes and inheritance; In essence, the class and extends keywords in ES6 are implemented using syntactic sugars)

JavaScript is flexible enough to even enable encapsulation of interfaces (similar to interface and implements in Java).

Second, the realization of the class

1. My understanding of the class

?? First of all, let me first talk about my understanding of the class: A class is a collection of "Properties/methods" that can be created from a class's constructor (for example, a human being is a class, and everyone is an instance object), and this instance object contains two things:

? A. All non-static "properties/Methods" of a class

??? A non-static "attribute/method" is unique to each instance and belongs to individuality. (for example, each person's name is not the same, and the Name property is a non-static property)

? B. All static "Properties/Methods" of a class

??? Static "Properties/Methods" are shared by each instance and are common. (for example, everyone has to eat, and eating is a non-static method)

2.Javascript implementation of the class

? A. Creating a class with a function, generating an instance object with the New keyword

? (not much to say, first on the code, the following is not specifically stated, I will first on the code, and then explain the explanation)

// 代码2.2.afunction Human() {    console.log(‘create human here‘)}var fakeperson = Human() // undefinedvar person = new Human() // {}

Here human is not only a normal function, but also a constructor of a class, when called Human (), it is executed as a normal function, will output create human here, but no return value (that is, return undefined), and when calling new Human () , it also outputs the create human here and returns an object. Because we use the human function to construct the object, we also call human a constructor. so by defining a constructor, it is equivalent to defining a class that, through the new keyword, generates an instantiated object.


? B. Using constructors to implement non-static "Properties/Methods"

// 代码2.2.bfunction Human(name) {    this.name = name}var person_1 = new Human(‘Jack‘)var person_2 = new Human(‘Rose‘)console.log(person_1.name)  // Jackconsole.log(person_2.name)  // Rose

There is one more parameter in the human constructor here and one more this.name = name in the function body, the this pointer in this sentence points to the instantiated object returned by the new keyword, so depending on the constructor parameter, the value of the property name in the resulting object is different. And the name here is the * * Non-static "properties/Methods" of this class * *


? C. Implementing static "Properties/Methods" with prototype

This is because we need to use the knowledge of the prototype chain, so put it behind the prototype chain.

Three, the prototype chain


? 1. What is the prototype of the class?

??? In JavaScript, whenever we define a constructor, the JavaScript engine automatically adds a prototype (also known as a prototype) to the class.

? **2. What is the __proto__ of the object? **

??? In JavaScript, whenever we create an object using new, the JavaScript engine automatically adds a __proto__ property to the object and points it to its class prototype

// 代码3.2function Human(name) {    this.name = name}console.log(Human.prototype)var person_test1 = new Human(‘Test1‘)var person_test2 = new Human(‘Test2‘)console.log(person_test1.__proto__)console.log(person_test2.__proto__)console.log(Human.prototype === person_test1.__proto__) // trueconsole.log(Human.prototype === person_test2.__proto__) // true

We will find that Human.prototype is an object, the human class is instantiated object Person_test1, Person_test2 has a property __proto__ is also an object, And they are all equal to Human.prototype, and we know that the equivalence of reference types in JavaScript means that they are pointing to the same object. So we can conclude that the __proto__ property of any instantiated object points to the prototype of its class.

**3. What is the __proto__ of the object? **

// 代码3.3var Pproto = {    name:‘jack‘}var person = {    __proto__:Pproto}console.log(person.name) // jackperson.name = ‘joker‘console.log(person.name) // joker

We found that at first we didn't define the name attribute for person, why did the console come out of Jack? This is the result of JavaScript's famous prototype chain. Talk not much, first:

What happened when we visited Person.name?
First it accesses the property of the person object itself, and if it does not define the Name property itself, it will look for its __proto__ Property object, in this case the __proto__ property of person corresponds to the Pproto object, so the person's __ proto__ points to Pproto, and then we find that the Pproto object has a name attribute, so person.name ends up and returns Jack, but what if we add a property name to the person? At this point, again person.name will not look for __proto__, because the person itself already has the Name property, and its value is joker, so here will return joker.


We notice that the __proto__ in Pproto point to object, because each object created by literal means is by default an object of the object class, so their __proto__ naturally point to Object.prototype.


? 4. Using prototype to implement static "Properties/Methods"

// 代码3.4function Human(name) {    this.name = name}Human.prototype.eat = function () {    console.log(‘I eat!‘)}var person_1 = new Human(‘Jack‘)var person_2 = new Human(‘Rose‘)person_1.eat() // I eat!person_2.eat() // I eat!console.log(person_1.eat === person_2.eat) // true

Here we write an extra sentence outside of the constructor: Human.prototype.eat = function () {...} so that each subsequent instantiation of an object through Human __proto__ Will point to Human.prototype, and according to the above prototype chain knowledge, we can know that as long as the constructor does not define a non-static "property/method" with the same name, then each object accesses the Say method, Access is actually the Human.prototype.say method, so that we use prototype to implement the static "Properties/Methods" of the class, all the objects achieve a common feature, that is eat

Iv. implementation of inheritance

1. My understanding of inheritance

?? If there are N (n>=2) classes, some of their "properties/methods" are different, but there are some "properties/methods" are the same, so we have to define each of them repeatedly to define these same "Properties/methods", that is not very annoying? So some of the most awesome programmers think that they can, like sons inherit their fathers ' genes, let these classes also "inherit" their "fathers" Like "sons" (and the father here contains the same "attributes/methods" that they have). So we can define a class that is called the parent class, which contains the same "Properties/methods" that all of these subclasses have, and then, by inheritance, all subclasses can access the properties/methods without having to define these "properties/methods" each time in the definition of the subclass.

2. Prototype chain implementation inheritance (let subclasses inherit the static "Properties/Methods" of the parent Class)

??

// 代码4.1function Father() {}Father.prototype.say = function() {    console.log(‘I am talking...‘)}function Son() {}var sonObj_1 = new Son()console.log(sonObj_1.say) // undefined// 原型链实现继承的关键代码Son.prototype = new Father()var sonObj_2 = new Son()console.log(sonObj_2.say) // function() {...}

See this sentence son.prototype = new Father () You may have a bit of a circle, that's all right, I'm going to start with a diagram of the prototype chain, you can understand it in minutes.

In the picture we think about, first of all, the beginning of Son, Father two classes have nothing to do, so when visiting say is definitely undefined, but when we use Son.prototype = new Father (), we know through New Son () The generated object will have the __proto__ property, and this property points to Son.prototype, and here we make it equal to a Father object, and the Father class also defines the static method say, so here our sonobj_2 by looking along the prototype chain, Find the Say method, so you can access to the Father class static method say. This enables subclasses to inherit the static "Properties/Methods" of the parent class, so how can subclasses inherit the non-static "properties/Methods" of the parent class?

3. Constructor implementation inheritance (let subclasses inherit non-Static "properties/Methods" of the parent Class)

// 代码4.3function Father(name) {    this.name = name}function Son() {    Father.apply(this, arguments)    this.sing = function() {        console.log(this.name + ‘ is singing...‘)    }}var sonObj_1 = new Son(‘jack‘)var sonObj_2 = new Son(‘rose‘)sonObj_1.sing() // jack is singing...sonObj_2.sing() // rose is singing...

In this example, by using the Apply function in the son's constructor, the father constructor is executed, so that every son object is instantiated with the Father constructor, which gets the Name property, so Every son object instantiated by son will have a different name attribute value, thus implementing a subclass that inherits the non-static "properties/Methods" of the parent class

4. Combination implementation Inheritance (combined prototype chain inheritance + constructor inheritance)

?? We can think about it first.

5. Parasitic combination to achieve inheritance

?? We can think about it first.

Understanding of JavaScript classes, prototype chains, 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.