preface

In ES5 they were prototype functions, but in ES6 the concept of “classes” was introduced. ES5 syntactic sugar, which makes writing code much faster, this article will cover only a few common (in fact, only a few attributes), let’s take a look at the class

The basic use

The keyword for defining a class is class, and this defines a class that, like our ES5 constructor, uses the new keyword

class Person {}const cateory = new Person() / / call the class
Copy the code

Class inheritance

In ES5, you’d have to use call or Prototype to inherit a method on a prototype or instance, but ES6 provides the extends keyword, which also extends methods and properties

class Person {
    name = "Front-end entertainment.";
    hello() {
        return "Hello"}}class Scholl extends Person {
    getName() {
        return this.name; }}const res = new Scholl();
console.log(res.getName()) // Front-end entertainment
console.log(res.hello()) / / how are you
Copy the code

Note: the class class declares attributes, and all methods are mounted to the prototype of the current class

constructor

Constructor, which is the constructor of the current instance. Only one constructor exists per class, and constructor is executed immediately when the class is instantiated (i.e., new). If a class does not define the constructor constructor, it is implicitly added to the class by default and returns the current class value. It is also possible to display a manual return that returns another reference value, in which case the current instance is the constructor return value.

// No write by default
class Person {}console.log(new Person()) // Default constructor points to its own instance

// show constructor
class Person1 {
    constructor(){}}console.log(new Person1()) // Explicitly write the constructor constructor. The instance object returns the current constructor

// Display the return object
class Person2 {
    constructor() {
        return{}}}console.log(new Person2()) // The return value of this instance is an empty object; the constructor return value must be an object
Copy the code

The super keyword

class Person {}class school extends Person {
    constructor() {
        super(a)// The Person class is inherited, but the super call must be used or an error will be reported.}}Copy the code

The school class inherits from the Person class and returns an error if the super keyword is not called from constructor. Because subclasses don’t have their own This object, they inherit this from their parent, where the super keyword is the Person object. Finally instantiation is returned by the school as an example, the super function internally Person. The prorotype. Call (this) constructor.

Note that the super function can only be executed once in the class, otherwise an error will be reported

This cannot be called before the super keyword

You cannot use this until super is called, or an error is reported. Because super hasn’t been called yet.

class Person {}class school extends Person {
    constructor() {
        console.log(this) / / error ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
        super()}}// Internal implicit operation
class school extends Person {
    constructor() {
        // console.log(this) // Error
        let _this = super(a);return_this; }}Copy the code

The above code, we said that can’t call this before super, but such as super Person. After a call prorotype. Constructor. Call (this), implicit return this. Returns the current instance object, at which point this is available and refers to the current instance.

The super keyword can also be used as an object

class Person {
	getName() {
		return "Front-end entertainment."
	}
}
Person.prototype.name = "Frogman"
Perosn.prototype.age = 18

class school extends Person {
    constructor() {
        const res = super(a)// Super refers to the Person class
        console.log(super.getName(), super.name) // The super keyword here points to Person.prototype
    }
    
    getAge() {
    	console.log(super.age)
    }
}
Copy the code

In the above code, the super function can have only one function, but the super keyword can be used as an object. The super keyword refers to the prototype object of the parent class. The super keyword can be used anywhere in a class, but the super function can only be used within Constructor.

Note: the super function returns an instance of the current class. The super keyword points to the prototype of the current class

get

It is used to get value properties. As we said earlier, private properties cannot be accessed outside of a class, but we can use the get keyword to get private properties inside a class.

class Person {
	private username = "Front-end entertainment.";
	private age = 18;
    get getVal() {
        return this.username; }}const res = new Person(); 
console.log(res.getVal) // Front-end entertainment
Copy the code

So let’s see how this get keyword is different from defining a method.

class Person {
	private username = "Front-end entertainment.";
	private age = 18;
    getVal() {
        return this.username; }}const res = new Person(); 
console.log(res.getVal()) // Front-end entertainment
Copy the code

We removed the get keyword above and called it with () to indicate that a function is to be executed. Although it has the same effect as get, it is not recommended for use in Vue, just as for computed writing, it is not recommended for use in Methods. The official definition of get is the value function, we can use the get keyword without writing (), just like getting an attribute.

set

Set = get = set = set = set A store function is the same thing as a value function.

class Person {
	private username = "Front-end entertainment.";
	private age = 18;
    get getVal() {
        return this.username;
    }

	set setVal(val) {
        this.username = val
    }
}
const res = new Person(); 
res.setVal = "Frogman"
console.log(res.getVal()) / / frogman
Copy the code

We saved the value and then evaluated it. As expected, we saved the value and changed the value of username.

Private property

Private attributes must be declared in a class starting with #. Attributes that begin with # are accessible only in the class, not outside the class. If you’re using TypeScript, you can use private instead.

class Person {
    #name = "Frogman"
    constructor(){}getName() {
        return this.#name
    }

	#getAge() {
    	return 18}}const res = new Person();
// console.log(this.#name) // An error was reported. This field must be declared in a closed class
console.log(res.getName()) / / frogman
console.log(res.#getAge) // getAge is not function
Copy the code

static

Static is a class property that can be accessed without instantiating the class. Properties and methods like ours that are not static must be instantiated in order to be called.

And a little bit of notice here, when we’re done defining

A property that is not static defined

class Person {
	username = "Front-end entertainment.";
	age = 18;
}
const res = new Person().username; // Front-end entertainment
Copy the code

For a non-static property like ours, you have to instantiate new to access the username property.

Static Specifies an attribute

Static defines a static property that can be accessed without instantiation. Not defined on instantiated objects.

// The old way of writing it
class Person {}
Person.username = "Front-end entertainment."

// add a static keyword
class Person {
	static username = "Front-end entertainment.";
	static age = 18;
	static getName() {
		return Person.username
	}
}

console.log(Person123.username, Person123.getName()) // Front-end entertainment, front-end entertainment
Copy the code

The previous static attributes were defined outside the class. Once the entire class is generated, it is regenerated into static properties. It’s easy to ignore this static attribute, and it doesn’t follow the code organization principle that related code should be kept together. To solve this problem, the new static keyword static method


These three modifiers are only available in TypeScript classes and are not supported in JavaScript classes.

public

Public is the public attribute of a class, which means that the attributes and methods in the class can be accessed either inside or outside the class. Properties and methods defined by default are public.

class Person {
	name = "Front-end entertainment.";
	public age = 18;
}
const res = new Person();
console.log(res.name, res.age) // Front-end entertainment 18
Copy the code

The name property does not define a public public property, so all properties and methods defined in the class are defined as public by default.

private

Private is the private property of a class and can only be accessed in the current class, which is the field inside {}. Properties and methods defined by private are not accessible outside {}

class Person {
	private name = "Front-end entertainment.";
	private age = 18;
}
const res = new Person();
console.log(res.name, res.age) The current property is private and can only be accessed inside the class

class Scholl extends Person {
    getData() {
        return this.username + "," + this.age
    }
}
const temp = new Scholl()
console.log(temp.getData()) The Person class is inherited, but the private definition is only accessible by the current class and not by subclasses.
Copy the code

protected

Protected is the protected property of a class. Only the current class and subclasses can access it. This means that subclasses defined with the protected property can also be accessed.

class Person {
	protected username = "Front-end entertainment.";
	protected age = 18;
}
const res = new Person();
console.log(res.name, res.age) The current property is private and can only be accessed inside the class

class Scholl extends Person {
    getData() {
        return this.username + "," + this.age
    }
}
const temp = new Scholl()
console.log(temp.getData()) // Front-end entertainment, 18. Properties of the parent class can be accessed normally
Copy the code

example

For example, if we write a small Demo popover below, we can write a separate class inside the class. This method looks more comfortable than the prototype method in ES5. Of course, in our daily development business, public methods can also be written into a class

class Mask {
  isShow = false;
  elem = null
  constructor() {
      this.elem = this.init()
  }
  
  init() {
    const oDiv = document.createElement("div");
    document.body.appendChild(oDiv);
    return oDiv;
  }
  
  show() {
    this.elem.style.display = "block"
    this.isShow = true;
  }
  
  hide() {
    this.elem.style.display = "none"
    this.isShow = false; }}Copy the code

conclusion

ES6’s class class is a syntactic sugar, so if you understand JavaScript’s concepts of objects and object-oriented thinking, it’s easy to understand.

Public account: front-end entertainment. Welcome to attention

Interested partners can join [front end entertainment exchange group] welcome to exchange and discuss

Phase to recommend

These operations remove console.log code, did you know?

Vue3: A guide to mastering the new features of Vue3

“How to write a Vue component to publish to NPM and import it for use outside chain”

12 Loaders used in Webpack

CommonJs and Es Module and the difference between them

Do you know all these JavaScript tips for your job?

[Suggested Collection] Share some common Git commands in work and how to solve special problem scenarios