javascript class

JavaScript class (class)

A class is a template for creating objects.

We use the class keyword to create a class, the class body is in a pair of braces {}, we can define the location of class members in the braces {}, such as methods or constructors.

Each class contains a special method constructor(), which is the constructor of the class. This method is used to create and initialize an object created by the class.

The syntax for creating a class is as follows:

class ClassName {
  constructor() { ... }
}

Example:

class Runoob {
  constructor(name, url) {
    this.name = name;
    this.url = url;
  }
}

The above example creates a class called "Runoob".

Two properties are initialized in the class: "name" and "url".

browser support

The numbers in the table indicate the version number of the first browser that supports the property.

Chrome 49 Edge 12 Firefox 45 Safari 9 Opera 36
Mar, 2016 Jul, 2015 Mar, 2016 Oct, 2015 Mar, 2016

use class

Once the class is defined, we can use the new keyword to create objects:

class Runoob {
  constructor(name, url) {
    this.name = name;
    this.url = url;
  }
}
 
let site = new Runoob("菜鸟教程",  "https://www.runoob.com");

The constructor method constructor() is automatically called when an object is created.

class expression

Class expressions are another way to define classes. Class expressions can be named or unnamed. The name of a named class expression is the local name of the class body.

// 未命名/匿名类
let Runoob = class {
  constructor(name, url) {
    this.name = name;
    this.url = url;
  }
};
console.log(Runoob.name);
// output: "Runoob"
 
// 命名类
let Runoob = class Runoob2 {
  constructor(name, url) {
    this.name = name;
    this.url = url;
  }
};
console.log(Runoob.name);
// 输出: "Runoob2"

Construction method

A constructor is a special method:

  • The constructor method is called constructor().
  • Constructors are automatically executed when creating a new object.
  • Constructors are used to initialize object properties.
  • If no constructor is defined, JavaScript automatically adds an empty constructor.

class method

We create a class using the keyword class, we can add a constructor() method, and then add any number of methods.

class ClassName {
  constructor() { ... }
  method_1() { ... }
  method_2() { ... }
  method_3() { ... }
}

In the following example we create an "age" method that returns the age of the website:

class Runoob {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
  age() {
    let date = new Date();
    return date.getFullYear() - this.year;
  }
}
 
let runoob = new Runoob("菜鸟教程", 2018);
document.getElementById("demo").innerHTML =
"菜鸟教程 " + runoob.age() + " 岁了。";

We can also send parameters to methods of classes:

class Runoob {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
  age(x) {
    return x - this.year;
  }
}
 
let date = new Date();
let year = date.getFullYear();
 
let runoob = new Runoob("菜鸟教程", 2020);
document.getElementById("demo").innerHTML=
"菜鸟教程 " + runoob.age(year) + " 岁了。";

Strict mode "use strict"

Both class declarations and the bodies of class expressions are executed in strict mode. For example, constructors, static methods, prototype methods, getters and setters are all executed in strict mode.

If you're not following strict mode, you'll get an error:

class Runoob {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
  age() {
    // date = new Date();  // 错误
    let date = new Date(); // 正确
    return date.getFullYear() - this.year;
  }
}

The example below uses variables that are not declared by the class:

For more strict modes, please refer to: JavaScript Strict Mode (use strict)

JavaScript class inheritance

JavaScript class inheritance uses the extends keyword.

Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application.

The super() method is used to call the constructor of the parent class.

When creating a class, you don't need to rewrite new data members and member functions, you only need to specify that the new class inherits the members of an existing class. This existing class is called the base class (parent class), and the newly created class is called the derived class (subclass).

Inheritance represents the is a relationship. For example, a mammal is an animal, a dog is a mammal, therefore, a dog is an animal, and so on.

code show as below:

// 基类
class Animal {
    // eat() 函数
    // sleep() 函数
};
 
 
//派生类
class Dog extends Animal {
    // bark() 函数
};

The class "Runoob" created by the following instance inherits the class "Site":

class Site {
  constructor(name) {
    this.sitename = name;
  }
  present() {
    return '我喜欢' + this.sitename;
  }
}
 
class Runoob extends Site {
  constructor(name, age) {
    super(name);
    this.age = age;
  }
  show() {
    return this.present() + ', 它创建了 ' + this.age + ' 年。';
  }
}
 
let noob = new Runoob("菜鸟教程", 5);
document.getElementById("demo").innerHTML = noob.show();

The super() method refers to the constructor of the parent class.

By calling the super() method in the constructor, we call the constructor of the parent class, so that we can access the properties and methods of the parent class.

Inheritance is useful for code reusability.

JavaScript does not have traditional classes like other programming languages, but a prototype-based inheritance model.

ES6 introduced classes and the class keyword, but the underlying mechanism is still based on prototypal inheritance.

Use prototype chain inheritance

In the following example, Animal is a base class, Dog is a subclass inherited from Animal, Dog.prototype uses Object.create(Animal.prototype) to create a new object, which inherits the methods and properties of Animal.prototype, Make sure the constructor is correct up the inheritance chain by setting Dog.prototype.constructor to Dog.

function Animal(name) {
  this.name = name;
}
 
Animal.prototype.eat = function() {
  console.log(this.name + " is eating.");
};
 
function Dog(name, breed) {
  Animal.call(this, name);
  this.breed = breed;
}
 
// 建立原型链,让 Dog 继承 Animal
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
 
Dog.prototype.bark = function() {
  console.log(this.name + " is barking.");
};
 
var dog = new Dog("Buddy", "Labrador");
dog.eat();  // 调用从 Animal 继承的方法
dog.bark(); // 调用 Dog 的方法

Use ES6 class inheritance

ES6 introduces the class keyword to make the definition of classes and inheritance clearer, the extends keyword is used to establish inheritance relationships, and the super keyword is used to call the constructor of the parent class in the subclass constructor.

class Animal {
  constructor(name) {
    this.name = name;
  }
 
  eat() {
    console.log(this.name + " is eating.");
  }
}
 
class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }
 
  bark() {
    console.log(this.name + " is barking.");
  }
}
 
const dog = new Dog("Buddy", "Labrador");
dog.eat();
dog.bark();

Whether you use prototype chain inheritance or ES6 class inheritance, similar inheritance effects can be achieved. When choosing which method, you can decide according to your personal preference and project requirements.

getter 和 setter

In the class, we can use getter and setter to get and set the value, both getter and setter need to be executed in strict mode.

Getters and setters can make our operations on properties very flexible.

Adding getters and setters to a class uses the get and set keywords.

The following example creates a getter and setter for the sitename property:

class Runoob {
  constructor(name) {
    this.sitename = name;
  }
  get s_name() {
    return this.sitename;
  }
  set s_name(x) {
    this.sitename = x;
  }
}
 
let noob = new Runoob("菜鸟教程");
 
document.getElementById("demo").innerHTML = noob.s_name;

Note: Even if the getter is a method, don't use parentheses when you want to get the property value.

The name of the getter/setter method cannot be the same as the name of the property, which in this case is sitename.

Many developers use the underscore character _ before the property name to separate the getter/setter from the actual property:

The following example uses the underscore _ to set properties and create corresponding getter/setter methods:

class Runoob {
  constructor(name) {
    this._sitename = name;
  }
  get sitename() {
    return this._sitename;
  }
  set sitename(x) {
    this._sitename = x;
  }
}
 
let noob = new Runoob("菜鸟教程");
 
document.getElementById("demo").innerHTML = noob.sitename;

To use a setter, use the same syntax as when setting a property value, although set is a method, without the parentheses:

class Runoob {
  constructor(name) {
    this._sitename = name;
  }
  set sitename(x) {
    this._sitename = x;
  }
  get sitename() {
    return this._sitename;
  }
}
 
let noob = new Runoob("菜鸟教程");
noob.sitename = "RUNOOB";
document.getElementById("demo").innerHTML = noob.sitename;

promote

An important difference between function declarations and class declarations is that function declarations hoist while class declarations do not.

You first need to declare your class before accessing it, otherwise code like the following will throw a ReferenceError:

// 这里不能这样使用类,因为还没有声明
// noob = new Runoob("菜鸟教程")
// 报错
 
class Runoob {
  constructor(name) {
    this.sitename = name;
  }
}
 
// 这里可以使用类了
let noob = new Runoob("菜鸟教程")

If there is no statement before use, an error will be reported:

It has been declared before use and can be executed normally:

JavaScript static methods

A static method is a method modified with the static keyword, also called a class method, which belongs to a class, but not an object. Before instantiating an object, a static method can be called through the class name. method name.

Static methods cannot be called on objects, only within classes.

class Runoob {
  constructor(name) {
    this.name = name;
  }
  static hello() {
    return "Hello!!";
  }
}
 
let noob = new Runoob("菜鸟教程");
 
// 可以在类中调用 'hello()' 方法
document.getElementById("demo").innerHTML = Runoob.hello();
 
// 不能通过实例化后的对象调用静态方法
// document.getElementById("demo").innerHTML = noob.hello();
// 以上代码会报错

When an instance object calls a static method, an error will be reported:

If you want to use a static method in an object noob, you can pass it as an argument:

class Runoob {
  constructor(name) {
    this.name = name;
  }
  static hello(x) {
    return "Hello " + x.name;
  }
}
let noob = new Runoob("菜鸟教程");
document.getElementById("demo").innerHTML = Runoob.hello(noob);

Guess you like

Origin blog.csdn.net/qq_32907491/article/details/132250227