Class Inheritance in Javascript

后端 未结 4 1244
醉酒成梦
醉酒成梦 2020-12-19 08:12

I am wondering how to simulate Class Inheritance in JavaScript. I know class doesn\'t apply to JavaScript, the way we use is Functions to create objects and do the inheritan

4条回答
  •  执念已碎
    2020-12-19 09:12

    There are plenty ways of implementing inheritance and behavior reuse in JavaScript, perhaps the way that is more similar to your class-based OOP example would be the pseudo-classical inheritance:

    function Mankind (name, lastname) {
      this.name = name;
      this.lastname = lastname;
    }
    
    function Person (name, lastname) {
      this.name = name;
      this.lastname = lastname;
    
      this.run = function() {
        // run logic
      };
    }
    Person.prototype = new Mankind();
    Person.prototype.walk = function () {
      // walk logic
    };
    

    The difference between run and walk is that the first will exist on every object instance of Person, and the second method, walk, will exist only in Person.prototype and will be accessed through the prototype chain.

    In this pattern you see a bit of code duplication, we need the logic to initialize the fields also on the inherited constructor, another pattern that avoids this, is Constructor Function application:

    function Mankind (name, lastname) {
      this.name = name;
      this.lastname = lastname;
    }
    
    function Person (name, lastname) {
      Mankind.apply(this, arguments);
      this.run = function() {
        // run logic
      };
    }
    

    More info:

    • How to inherit from a class in JavaScript (various examples)
    • Inheritance Patterns in JavaScript (article)
    • Classical Inheritance in JavaScript (article)

提交回复
热议问题