B station video learning and network es6 learning
Some ways to use classes in ES6 and what to note when using them
Basic writing of class 1
constructor(name,age ) { this.name =name ; this.aeg =age ; } say() {console.log()}} let p1=new Person('zs',23) console.log(p1)Copy the code
The output is:
Methods and properties in class 2
class Person {
constructor(name,age ) {
this.name =name ;
this.aeg =age ;
}
a=1
say() {
console.log('Lao wang')}}let p1=new Person('zs'.23)
console.log(p1)
Copy the code
As you can see, the say() method is defined on the prototype of instance P1. This allows instance to invoke the methods defined in class definition via point syntax. Properties defined outside the constructor are not defined on the prototype but as properties of the instance.
3 Static Methods
An instance inherits a method from a class through a stereotype. We can define a method as static. Methods defined in this way are not inherited and can only be called directly from the class
static classMethod() {
return 'hello'
}
}
Foo.classMethod() // 'hello'
Copy the code
4 this point
The this of a method in a class refers to an instance by default
const { say } = p1;
say();
Copy the code
At the same time, we print this in say, which refers to the runtime environment, and the single output is not window but undefine. This is because blocks of code in a class turn strict mode on by default whenever the class’s syntax is used
The problem can be solved in the following way
- 1 can accept this in a class by defining the global that variable
- Bind: this.say = this.say.bind(this)
- 3. Use the arrow function directly
class Obj {
constructor() {
this.logThis = () => this;
}
}
const myObj = new Obj();
myObj.logThis() // Obj{}
Copy the code
The this inside the arrow function always points to the object at which it was defined. In the above code, the arrow function is inside the constructor, and its definition takes effect when the constructor executes. In this case, the arrow function must be running in an instance object, so this will always point to an instance object.
Class 5 inheritance
Classes can be inherited through the extends keyword, which is much cleaner and more convenient than ES5’s inheritance through modified prototype chains.
class Father {
}
class Son extends Father {
}
Copy the code
The super keyword appears in both the constructor method and the toString method, where it represents the constructor of the superclass and is used to create the this object of the superclass.
Subclasses must call the super method from the constructor method or they will get an error when creating a new instance. This is because the subclass’s this object must be molded by the parent’s constructor to get the same instance attributes and methods as the parent, and then processed to add the subclass’s instance attributes and methods. If you don’t call super, your subclasses don’t get this. This is why the super keyword must come before this.