Explanation of JavaScript classes

Source: Internet
Author: User
Tags deprecated inheritance new set es6 class
Preface

life has a degree, life Tim Longevity.

Original address: detailed JavaScript class

Bo Main Blog Address: Damonare's personal blog

JavaScript from the original "window language", a step-by-step development of the now and then end of the monster. JavaScript is also growing in popularity, and this year the most popular programming language is the flowering JavaScript, which is a vibrant language. Today, with no more than thousands of lines of JavaScript code on a Web page, there are more than thousands of lines on the node back end. The primary problem with programming (WTF) increases in code is how to write and maintain such a large amount of code. The answer is modular thinking, in fact, object-oriented (OOP) programming, now the more popular three front-end framework (ANGULAR,REACT,VUE) are basically implemented component programming, but the component and what we call modularity is different, should be able to understand this, component is modular upgrade version, Modularity is the basis of component. So, here's the question, how is JavaScript object-oriented programming? I think that a lot of old birds also can not say clearly, the front-end miscellaneous and active in various communities, many front-end er once relied on a variety of plug-ins, do not need to understand these deep things are still able to complete the task. But I think as a pursuit of the front of the ER is still very necessary to learn these seemingly unnecessary things, others do not say, simply because we are front-end er, only with jquery a slightly more powerful backend can replace you. OK, nonsense not much to say, in the end how to object-oriented coding ...

Unfortunately, ES5 does not give a clear definition of ' class ' concept, so traditional object-oriented programming does not seem to work, then it should be swollen. Fortunately, the predecessors through continuous exploration and summary, the successful use of JavaScript simulation of the "class." So how do you define JavaScript classes?

in object-oriented Programming, classes (Class) are templates of objects (object) that define properties and methods that are common to the same set of objects (also known as "instances"). Body

When it comes to "classes" in JavaScript, we have to say that the prototype chain and inheritance, because JavaScript is not really a class, the so-called class is based on the prototype chain and inheritance to implement, even if the ES6 added class,extends keyword implementation class and inheritance, But in fact it is based on prototype chains and inheritance, and the ES6 class (class) is the syntactic candy inherited by JavaScript's existing prototype. 1. Prototype chain and inheritance


In JavaScript, each object has an internal link to its prototype (prototype) object. The prototype object has its own prototype until an object's prototype is null (i.e. no longer has a prototype pointing to it), forming the last loop of the chain. This first-level chain structure is called the prototype chain (prototype chain).

prototype chain

In fact, when you define an object, the prototype chain itself has been generated, and JavaScript's object-specific ideas are easy to understand here, and you'll find that everything starts with object.prototype. So how do we define an object, and bloggers summarize the following methods:

First to start a demo specifically explain the prototype chain is what it is:

Someobject. The [[Prototype]] symbol is the prototype used to assign the someobject. This is equivalent to JavaScript's __proto__  attribute (now deprecated) ... Starting with ES6, [[Prototype]] can be accessed using object.getprototypeof () and object.setprototypeof () accessors. This method can be assured of using the Bo Master Pro test, the mainstream browser has supported
//assumed that there is an object o, its own properties (own properties) have A and B:
//{a:1, b:2}
//o prototype O.[[prototype] There are attributes B and C:
//{b:3, c:4}
//Finally, o.[[prototype]].[ [Prototype]] Is null.
This is the end of the prototype chain, that is, NULL,
//By definition, NULL is not [[Prototype]].
In summary, the whole prototype chain is as follows:
//{a:1, b:2}---> {b:3, c:4}---> Null

Come on, let's get an object out of the sleeves. (Immediate dog day, single dog please read this blog consciously) use the common method to create an object

demo as follows:

var o={
    a:0,
    b:function () {
        console.log (THIS.A)
    }
}
//Create an object
//prototype chain as follows:
//o---> Object.prototype--->null
var a = ["Yo", "whadup", "?"];
Create an Array object
//(IndexOf, foreach, and so on are inherited from it).
The prototype chain is as follows:
//a--->array.prototype---> object.prototype---> Null
function f () {return
  1;
}
//Create a Function object
//(call, Bind, etc methods inherit from it):
//Prototype chain is as follows:
//f---> Function.prototype---> Object.prototype---> Null
var date=new date ();
Create a Date object
//prototype chain as follows:
//date--->date.prototype--->object.pprototype--->null
Methods that use constructors

In JavaScript, the constructor is actually a normal function. When you use the new operator to function This function, it can be called the constructor method (constructor). --mdn

demo as follows:

function Fun () {
    this.propa= ' prop ';
    this.propb=3;
}
fun.prototype={
    methoda:function () {
        console.log (this.propa)
    }
}
var o=new fun ();
O.methoda ();//prop

//O is the generated object, and his own attributes are ' propa ' and ' PROPB '.
When O is instantiated, O.[[prototype]] points to fun.prototype.
Creating objects using Object.create

A new method has been introduced in ECMAScript 5: object.create (). You can call this method to create a new object. The prototype of the new object is the first argument passed in when the Create method is invoked:

var a = {a:1};
A---> object.prototype---> null

var b = object.create (a);
b---> A---> object.prototype---> Null
console.log (B.A);//1 (inherited) concept of inheritance The following will speak

var C = object.create (b);
c---> B---> A---> object.prototype---> null

var d = object.create (null);
D---> Null
console.log (d.hasownproperty);//undefined, since D does not inherit Object.prototype
Use the class keyword

ECMASCRIPT6 introduced a new set of keywords to implement class. Developers who use a class-based language are familiar with these constructs, but they are not the same. JavaScript is still based on prototypes. These new keywords include class, constructor, static, extends, and super.

"Use strict";

Class Polygon {
  constructor (height, width) {
    this.height = height;
    This.width = width;
  }
}
Defines a class-Polygon class
Square extends Polygon {
  Constructor (sidelength) {
    super (sidelength, sidelength);
  } Use Super to refer to parent class get area
  () {return
    this.height * this.width;
  }
  Set Sidelength (newlength) {
    this.height = newlength;
    This.width = newlength;
  }
Using the extends definition Squeare inherits the parent class polygon
var square = new Square (2);//instance Object

//The prototype chain at this point is:
//square---> Square.prototype--->polygon.prototype--->object.prototype--->null
//If you don't understand why, don't look down the description of the class
inherited

In fact, when it comes to the prototype chain, it's hard to avoid mentioning inheritance, such as the example from MDN:

//assumes an object o, its own properties (own properties) have A and B://{a:1, b:2}//O's prototype O.[[prototype]] has attributes B and C: (s Omeobject. The [[Prototype]] symbol is the prototype used to assign the someobject. This is equivalent to JavaScript's __proto__ attribute (now deprecated) ... Starting with ES6, [[Prototype]] can be accessed using object.getprototypeof () and object.setprototypeof () accessors. )//{b:3, c:4}//Finally, O.[[prototype].
[[Prototype]] is null.
This is the end of the prototype chain, that is, NULL,//By definition, NULL is not [[Prototype]]. Fully, the whole prototype chain is as follows://{a:1, b:2}---> {b:3, c:4}---> Null console.log (O.A); 1//A is the own property of O. Yes, the value of this property is 1 console.log (O.B); 2//b is the own property of O.

Yes, the value of this property is 2//o.[[prototype]] and there is also a ' B ' attribute, but it is not accessed. This situation is called property shadowing. Console.log (O.C); 4//C is the own property of O. No, look at the O.
[[Prototype]] there's no. C is O. [[Prototype]] 's own properties. Yes, the value of this property is 4 Console.log (O.D); Undefined//d is the own property of O. No, look at the O.
[[Prototype]] there's no. D is O. [[Prototype]] 's own properties. No, look at the O. [[Prototype]].
[[Prototype]] there's no. O.[[prototype]]. [[Prototype]] is null, stop search,//No D property, return undefined 

--The above content from MDN inheritance and prototype chain

I want to see some indefinitely here, so let's take an example:

var object1={
    a:1,
    b:function () {
        console.log (this.a+1);
    }
}
Defines an object
var object2=object.create (object1);
Call Object.create to create a new object, the prototype of which is the first argument passed in when the Create method is invoked, and now the prototype chain is:
//object2--->object1---> Object1.prototype--->null
object2.d=4;
object2.a;
1
//inherited the Object1 attribute a
object2.b ();
2
//inherited the Object1 method B
object.getprototypeof (OBJECT2);
Object1 gets Object2 's prototype Object1

I think it should be clear now, do not understand the blogger is powerless, the ability to express is limited. 2. Class

Finally, when it comes to classes, because JavaScript classes are based on prototype chaining and inheritance, a lot of the classes are already defined in the above content. Our JavaScript class can also implement the traditional classes of polymorphism, encapsulation, inheritance, and so on, which mainly explains the concept of inheritance, but in fact many times inadvertently may use these three features. It's fun, isn't it?

First, let's look at the form of a class defined in ES5:

function Animal (name) {
    this.name = name;
    This.sleep = function () {
        console.log (this.name+ ' sleeping ');
    }
Define Animal class
Animal.prototype = {
    eat:function (food) {
        console.log (this.name+ "eating" +food);
    }
function Cat () {

}
Cat.prototype = new Animal (' Tom ');
var Tom = new Cat (' Tom ');/cat instance Object
tom.eat (' cat food ');
Tom is eating cat food
//Inheritance Animal method
tom.sleep ();
Tom is sleeping
//Inheriting animal method
//Now prototype chain:
//tom (Cat instance object)--->cat.prototype (animal instance object)---> Animal.prototype--->object.prototype--->null

OK, then let's look at the rewrite of the above class in ES6:

Class Animal {
  constructor (name) {
    this.name = name;
  }

  Sleep () {
    console.log (this.name + ' sleeping ');
  }
  Eat (food) {
    console.log (this.name+ ' eating ' +food)  
  }
}

class Cat extends Animal {

}

const TOM = New Cat (' Tom ');
Tom.eat (' cat food ');
Tom is eating cat food
//Inheritance Animal method
tom.sleep ();
Tom is sleeping
//Inheriting animal method
//Now prototype chain:
//tom (Cat instance object)--->cat.prototype (animal instance object)---> Animal.prototype--->object.prototype--->null

The method of defining a class is actually the method of defining an object as described above, and the class itself is an object, except that the methods and attributes within the object can be invoked by many instance objects. PostScript

In general, the understanding of the class or need to continue to explore the road long its repair far XI, I will be up and down and searching.

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.