Simple use of javascript class encapsulation based on ECMAScript 6, ECMAScript 2015

Simple use of javascript class encapsulation based on ECMAScript 6, ECMAScript 2015

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 using the this keyword.

Then define two functions fun1 and fun2 in the class of Polygon, and output the input parameters.

/**
 * Create two JS classes and define a constructor
 */

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, width);
    this.name = 'Square';
  }
}
Create an html page file

<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="test.js" type="text/javascript"></script>
<script type="text/javascript">
	// create object
	var polygon1 = new Polygon(10, 15);
	var polygon2 = new Polygon(20, 30);

	polygon1.fun1();
	polygon1.fun2();

	polygon2.fun1();
	polygon2.fun2();

	var square = new Square(35, 36);
	square.fun1();
	square.fun2();
</script>
</head>
<body>
	<a href="https://Developer. Mozilla. Org / en US / docs / Web / JavaScript / reference / statements / class "> reference code</a>
</body>
<script type="text/javascript">
	
</script>

</html>
Output results

// polygon1.fun1() output
fun1 Polygon 10 15

// polygon1.fun2() output
fun2 Polygon 10 15

// polygon2.fun1() output
fun1 Polygon 20 30

// polygon2.fun2() output
fun2 Polygon 20 30

// square.fun1() output
fun1 Square 35 36

// square.fun2() output
fun2 Square 35 36

We can see that the class of javascript runs exactly as expected, showing polygon's fun and Square's fun correctly. This definition is very similar to the class definition of C++/Java, which conforms to the concept of class encapsulation. The back-end programmers can use javascript completely with the idea of class, and will no longer feel that the previous javascript language is slightly weird (from C++/Java Syntax point of view), for C++/Java programs need to take into account javascript programs is the gospel.



Tags: Javascript Java ECMAScript

Posted on Tue, 05 May 2020 02:29:55 -0700 by bdbush