Accessing member of base class

后端 未结 2 355
忘了有多久
忘了有多久 2021-01-30 11:52

See the inheritance example from the playground on the TypeScript site:

class Animal {
  public name;
  constructor(name) {
    this.name = name;
  }
  move(mete         


        
2条回答
  •  离开以前
    2021-01-30 12:32

    You are incorrectly using the super and this keyword. Here is an example of how they work:

    class Animal {
        public name: string;
        constructor(name: string) { 
            this.name = name;
        }
        move(meters: number) {
            console.log(this.name + " moved " + meters + "m.");
        }
    }
    
    class Horse extends Animal {
        move() {
            console.log(super.name + " is Galloping...");
            console.log(this.name + " is Galloping...");
            super.move(45);
        }
    }
    
    var tom: Animal = new Horse("Tommy the Palomino");
    
    Animal.prototype.name = 'horseee'; 
    
    tom.move(34);
    // Outputs:
    
    // horseee is Galloping...
    // Tommy the Palomino is Galloping...
    // Tommy the Palomino moved 45m.
    

    Explanation:

    1. The first log outputs super.name, this refers to the prototype chain of the object tom, not the object tom self. Because we have added a name property on the Animal.prototype, horseee will be outputted.
    2. The second log outputs this.name, the this keyword refers to the the tom object itself.
    3. The third log is logged using the move method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);. Using the super keyword in this context will look for a move method on the prototype chain which is found on the Animal prototype.

    Remember TS still uses prototypes under the hood and the class and extends keywords are just syntactic sugar over prototypical inheritance.

提交回复
热议问题