Create class and class inheritance in JavaScript

Create class and class inheritance in JavaScript

JavaScript is an object-oriented language. Reference data types are all objects, including functions as well. At the same time, objects can be customized through Object objects.
However, compared with other object-oriented languages ​​(such as Java and other high-level languages), there is also a big difference. JS has no concept of classes or interfaces, that is, abstract classes cannot be defined directly, and inheritance cannot be directly implemented. However, for the convenience of programming, we can simulate the behavior of classes and inheritance in JS.
Simply put, there is no concept of classes in Javascript, but it can use constructors to implement class functions. The constructor is a function, and the general constructor The first letter of the name is capitalized.
In fact, a class is a "special function". Just like the function expressions and function declarations you can define, there are two ways to create a class:

  1. Method 1: Class declaration
class Star {
  constructor(name, age) {
	    this.name = name;
	    this.age = age;
  }
}
  1. Method 2: Class expression
var Star = class {
       constructor(name, age) {
            this.uname = name;
            this.age = age;
       }
}
console.log(Star.name);  //Star

Note here: An important difference between function declarations and class declarations is that function declarations will be promoted, while class declarations will not . You need to declare your class first, and then access it, otherwise code like the following will throw a ReferenceError

var p = new Star(); // ReferenceError
class Star {
	constructor(name, age) {
            this.uname = name;
            this.age = age;
    }
} //要先声明类,才能使用它

The class must use the new keyword to instantiate

var ldh = new Star("刘德华", 55);
var zxy = new Star("张学友", 25);
console.log(ldh.name, ldh.age);  //刘德华,55
console.log(zxy.uname, zxy.age);  //张学友, 55
  1. Class inheritance
//语法
          class Father{

          }
          class Son extends Father{
        		//子类继承父类
          }
class Father {
            constructor() {

            }
            money() {
                console.log(100);
            }  //给类中添加了方法
}
class Son extends Father {

}
var son = new Son();
son.money();  //100(继承了父亲的100元)
class Father {
            constructor(x, y) {
                this.x = x;
                this.y = y;
            }
            sum() {
                console.log(this.x + this.y);
            }
}
class Son extends Father {
            constructor(x, y) {
                super(x, y);
                //super关键字用于访问和调用对象父类上的函数,可以调用父类的构造函数,也可以调用父类的普通函数
            }
}
var son = new Son(1, 2);
son.sum();

Guess you like

Origin blog.csdn.net/Angela_Connie/article/details/110536716