Search code examples
javascriptprototype

Prototypes and Class/Constructor/Object Members


I am quite confused about the prototype chain and inheritance in JavaScript. The Date() object for example has the member methods/functions such as Date.now(). Why is it then when you create a new instance of the Date() object, and call the now() method, it throws an error? new Date.now() But when calling a prototype method such as getTime, caling new Date().getTime() works but not Date().getTime() without creating a new instance. Why is that? I had an understanding that prototypes of objects become part of the original object? For example:

function Person(firstName, lastName) {
     this.firstname = firstName;
     this.lastname = lastName;
     this.getfirstName = () => {
              return this.firstName;
     }
}

Person.prototype.getlastName = () => {
      return this.lastName;
}

Doesn't the prototype method getlastName become a member method of Person and can be accessed without using the new keyword like how it must be used with getTime() for Date()?


Solution

  • Prototype adds an instance method, meaning it gets attached to instances of the class. For your example, the function getlastName will only be called like so:

    var p = new Person("first","last");
    p.getlastName();
    

    or

    new Person("first","last").getlastName();
    

    If you want getlastName to be attached to the class itself, you needn't use Prototype :

    Person.getlastName = () => { return this.lastName }
    

    In the case of the Date class, now is a static method (does not use Prototype) while getTime is an instance method (uses Prototype). You can see it in its documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

    Here's a reference to static and prototype methods: http://blog.anselmbradford.com/2009/04/09/object-oriented-javascript-tip-creating-static-methods-instance-methods/