Javascript functional inheritance with prototypes

后端 未结 4 1720
心在旅途
心在旅途 2021-02-01 08:58

In Douglas Crockford\'s JavaScript: The Good Parts he recommends that we use functional inheritance. Here\'s an example:

var mammal = function(spec, my         


        
4条回答
  •  暖寄归人
    2021-02-01 09:20

    Let me introduce you to Classical Inheritance that never uses prototype. This is a bad coding exercise but will teach you the real Classical Inheritance which always compared to prototypal inheritance:

    Make a custructor:

    function Person(name, age){
      this.name = name;
      this.age = age;
      this.sayHello = function(){return "Hello! this is " + this.name;}
    }
    

    Make another cunstructor that inherits from it:

    function Student(name, age, grade){
      Person.apply(this, [name, age]);
      this.grade = grade
    }
    

    Very simple! Student calls(applies) Person on itself with name and age arguments takes care of grade arguments by itself.

    Now lets make an instance of Student.

    var pete = new Student('Pete', 7, 1);
    

    Out pete object will now contain name, age, grade and sayHello properties. It owns all those properties. They are not uplinked to Person through prototype. If we change Person to this:

    function Person(name, age){
      this.name = name;
      this.age = age;
      this.sayHello = function(){
        return "Hello! this is " + this.name + ". I am " this.age + " years old";
      }
    }
    

    pete will no recieve the update. If we call pete.sayHello, ti will return Hello! this is pete. It will not get the new update.

提交回复
热议问题