Emulate super in javascript

后端 未结 11 1154
生来不讨喜
生来不讨喜 2020-12-08 10:18

Basically is there a good elegant mechanism to emulate super with syntax that is as simple as one of the following

  • this.$super.prop()
11条回答
  •  广开言路
    2020-12-08 10:55

    I think I have a more simple way....

    function Father(){
      this.word = "I'm the Father";
    
      this.say = function(){
         return this.word; // I'm the Father;
      }
    }
    
    function Sun(){
      Father.call(this); // Extend the Father
    
      this.word = "I'm the sun"; // Override I'm the Father;
    
      this.say = function(){ // Override I'm the Father;
        this.word = "I was changed"; // Change the word;
        return new Father().say.apply(this); // Call the super.say()
      }
    }
    
    var a = new Father();
    var b = new Sun();
    
    a.say() // I'm the father
    b.ay() // I'm the sun
    b.say() // I was changed
    

提交回复
热议问题