Is there a “right” way to do inheritance in JavaScript? If so, what is it?

后端 未结 5 855
再見小時候
再見小時候 2021-02-02 02:32

I have been trying to learn how to add testing to existing code -- currently reading reading Working Effectively With Legacy Code. I have been trying to apply some of the princ

5条回答
  •  闹比i
    闹比i (楼主)
    2021-02-02 03:24

    Prototype offers its own take on inheritance, from http://www.prototypejs.org/api/class/create:

    var Animal = Class.create({
      initialize: function(name, sound) {
        this.name  = name;
        this.sound = sound;
      },
    
      speak: function() {
        alert(this.name + " says: " + this.sound + "!");
      }
    });
    
    // subclassing Animal
    var Snake = Class.create(Animal, {
      initialize: function($super, name) {
        $super(name, 'hissssssssss');
      }
    });
    

提交回复
热议问题