class Parent {
// This in the constructor refers to itself
constructor(name) {
console.log(this.'This in the constructor defaults to an instance');
this.name = name;
}
Classes can call static methods, but instances of classes cannot
static create() {
// Note that if a static method contains the this keyword, this refers to the class, not the instance.
console.log(this.name); //Person
return 'I'm a static method of my superclass'
}
speak() {
return this.name
}
}
// With the extends keyword, the parent class inherits from the child class
class Child extends Parent {
constructor(name, age) {
/* the super keyword should appear only in subclass constructor. You must call super() inside the constructor of the subclass, Super ([arguements]) is used to access the constructor of the parent class. Super.parentfunction ([arguements]) is used to access the method of the parent class. Super ([arguements]) generates an empty object. Constructor is called as context and returns this object. Context as a subclass of constructor continues to call the constructor. Constructor */
super(name);
/ * is equivalent to the Parent in the prototype. The constructor. Call. (this name), or the Parent call (enclosing name) * /
this.age = age;
}
static create(name, age) {
return new Child(name, age)
}
showAge() {
return this.age;
}
showName() {
return this.name;
}
showParentFn() {
return super.speak()
/ / equivalent to
//return Parent.prototype.speak.call(this)}}let parent = new Parent("wgh");
let child = new Child("cym".24)
Parent.create(); // I am a static method of the parent class
parent.speak(); //wgh
child.showAge(); / / 24
child.showName(); //cym
child.showParentFn(); //cym
// Subclasses can call methods on their parent class
child.speak(); //cym
Copy the code