Simple use of JavaScript class class encapsulation based on ECMAScript 6, ECMAScript 2015
Article source blog.csdn.net/joyous/article/details/79102169
Create a JS file test.js
In the following example, we first define a class named Polygon, and then inherit it to create another class named Square. Note that the super () used in the constructor can only be used in the constructor and must be invoked before the This keyword is used.
And then define two functions fun1 and fun2 in the class of Polygon, and output constructs the parameters passed in.
/**
* Create two JS class and define a constructor (constructed)
/class Polygon {
//constructor
constructor (height, width) {
this.name = ' Polygon ';
this.height = height;
This.width = width;
}
fun1 function
fun1 () {
console.log (' fun1 ', this.name, This.height, this.width);
fun2 function
fun2 () {
console.log (' fun2 ', this.name, This.height, this.width);
}
Define square class and extend Polygon
class Square extends Polygon {
constructor (height, width) {
super (height, WI DTH);
this.name = ' Square ';
}
Create an HTML page file
<! doctype>
Output results
POLYGON1.FUN1 () output
fun1 Polygon
//polygon1.fun2 () output
fun2 Polygon
//polygon2.fun1 () output
FUN1 Polygon
//polygon2.fun2 () output
fun2 Polygon/
/square.fun1 () output
fun1 square
SQUARE.FUN2 () output
fun2 Square 35 36
The above test is based on Google Chrome Ver63, we can see the JavaScript class exactly as expected to run, the correct display of polygon fun and Square fun, this definition and c++/Java class set The semantic approach is very similar, conforming to the class encapsulation concept that the back-end programmer can use JavaScript entirely with class, and no longer feels that the previous JavaScript syntax is slightly inappropriate (from a C++/java syntax perspective), for C++/java programmers need to take into account The JavaScript program is simply the gospel. Article source blog.csdn.net/joyous/article/details/79102169
Q Group discussion: 236201801