Is there a good use case for the constructor property in Javascript?

前端 未结 3 1474
别那么骄傲
别那么骄傲 2020-12-01 19:47

First off, this question is not \"what does the constructor property do?\" - There\'s plenty of good documentation on exactly what it is and how it works: It\'s a r

3条回答
  •  失恋的感觉
    2020-12-01 20:46

    One of the good use cases is implementation of "inheritance" and "classes in javascript. Let's consider the following example:

    // define the Person Class
    function Person() {}
    
    Person.prototype.walk = function(){
      alert ('I am walking!');
    };
    Person.prototype.sayHello = function(){
      alert ('hello');
    };
    
    // define the Student class
    function Student() {
      // Call the parent constructor
      Person.call(this);
    }
    
    // inherit Person
    Student.prototype = new Person();
    
    // correct the constructor pointer because it points to Person
    Student.prototype.constructor = Student;
    
    // replace the sayHello method
    Student.prototype.sayHello = function(){
      alert('hi, I am a student');
    }
    
    // add sayGoodBye method
    Student.prototype.sayGoodBye = function(){
      alert('goodBye');
    }
    
    var student1 = new Student();
    student1.sayHello();
    student1.walk();
    student1.sayGoodBye();
    
    // check inheritance
    alert(student1 instanceof Person); // true 
    alert(student1 instanceof Student); // true
    

    As you can see we've inherited Person, by reassigning Student.prototype to new Person();, but then we need to reassign constructor back to Student as we want to create instance of Student class, but not a Person.

    UPDATE

    Btw, more real-world example of inheritance in javascript is to use intermediate function, so Person object will not be created during definition stage:

    // inherit Person
    function F() {}
    F.prototype = Person.prototype;
    Student.prototype = new F();
    

提交回复
热议问题