Constructor concept in javascript

后端 未结 5 1461
终归单人心
终归单人心 2021-02-03 12:33

In one of my questions, I got the following code as one of the answers. My understanding of the language has come has come a far better now, just have one small question.

<
5条回答
  •  悲&欢浪女
    2021-02-03 13:00

    There appear to be some holes in your understanding. Hopefully I can help.

    First, the traditional conventional syntax for a constructor function is function CapitalisedFunctionName()

    function Person() {
      this.firstName = "";
      this.lastName = "";
    }
    

    Note: this is not an object. From your question this isn't clear you understand that.

    At this point you can add to the prototype from which all new objects created from that constructor will inherit. This modified method from your example will be available to all new objects.

    Person.prototype.fullname = function () { 
      return this.firstName + " " + this.lastName;
    }
    

    Now, the constructor function allows you to create new object instances. So when you write:

    var perObj = new person();
    

    you are calling the constructor function, creating a new object instance, and assigning that instance to the perObj variable.

    When you create a new object instance the object contains the firstName and lastName properties which can be accessed like so:

    perObj.firstName;
    perObj.lastName;
    

    Note at the moment these have only empty strings assigned to them.

    And you can call that method too:

    perObj.fullname();
    

    But, again, at this point, perObj.fullname(); won't give you anything because firstName and lastName are empty strings.

    You can either define them like you have in your example: `perObj.lastName = 'Jones', or you could even change the way you create the object in the first place which is often the preferred method:

    Consider this:

    function Person(first, last) {
      this.firstName = first;
      this.lastName = last;
    }
    
    var perObj = new Person('Dave', 'Jones');
    

    Now perObj will have those properties prefilled:

    perObj.firstName // Dave
    perObj.lastName // Jones
    perObj.fullname() // Dave Jones
    

提交回复
热议问题