Classes and objects

1. Define the class

1.1 How to define a class before ES6?

  Before ES6, defining a class was done primarily through constructors
  function Person(){
     // Instance properties
     this.name='Joe';
     // Instance method
     this.say = function(){
        console.log(`my name is The ${this.name}`);
     }
     // Static attributes
     Person.age = 18;
     // Static method
     Person.run = function(){
       console.log('run'); }}let p = new Person(); // instantiate the object
   console.log(p.name);// Get instance attributes
   p.say();// Call the instance method
   console.log(Person.age);// Get static attributes
   Person.run();// Call static methods
Copy the code

1.2 How to define a class in ES6?

// Since ES6, the system has provided a keyword named class. This keyword is specifically used to define classes
class Person{
   // When we create objects from new, the system automatically calls constructor
   // constructor is what we call a constructor
   constructor(myName, myAge){
       // Add instance attributes in ES6 standard need to be added in constructor
       // Instance properties
       this.name = myName;
       this.age = myAge;
   }
   // Instance method
   say(){
      console.log(this.name, this.age);
   }
  // The following way of defining "static properties" is not in the official ES6 standard and is not supported by most browsers
  Static only supports static methods but does not support static attributes
  // Static attributes
  static num = Awesome!;
  // Static method
  static run() {
      console.log("run"); }}Copy the code

2. The inheritance

2.1 Inheritance prior to ES6

//1. Use the parent constructor in a subclass through the call/apply method
function Person(myName, myAge) {
     this.name = myName;
     this.age = myAge;
}
Person.prototype.say =  function () {
   console.log(this.name, this.age);
}
function Student(myName, myAge, myScore) {
      Person.call(this, myName, myAge);
      this.score = myScore;
      this.study = function () {
          console.log("day day up"); }}// 2. Set the prototype object of the subclass to the instance object of the parent class
 Student.prototype = new Person();
 Student.prototype.constructor = Student;
 let stu = new Student("zs".18.99);
 stu.say();
Copy the code

2.2 Inheritance of ES6

In ES6, how to inherit 1.1 add extends after a subclass and specify the name of the parent class 1.2 Invoke the parent class constructor */ via the super method in the subclass constructor */
class Person{
    constructor(myName, myAge){
        // this = stu;
        this.name = myName; // stu.name = myName;
        this.age = myAge; // stu.age = myAge;
    }
    say(){
       console.log(this.name, this.age); }}class Student extends Person{
    constructor(myName, myAge, myScore){
         super(myName, myAge);
         this.score = myScore;
    }
    study(){
        console.log("day day up"); }}let stu = new Student("zs".18.98);
stu.say();
Copy the code