How do I create a new method for a constructor?

Asked

Viewed 63 times

6

There is a Date constructor (which is the date constructor that already comes in JS), and I would like to create a lastYear() method that brings the "year = year-1" (for example and learning purposes).

I know I might as well do it using the prototype:

Date.prototype.lastYear = function(){
  return this.getFullYear() - 1;
}

console.log(new Date('1900-10-10').lastYear());

However, this way I learned in the books that this is not healthy for Compiler, since you are changing the natural prototype chain of javascript.

So I’d like to understand how I could do this in the best way using classes:

class Newfunc {
  constructor(){
    this.Date = Date
    this.lastYear();
  }

  lastYear(Date) {
    return this.Date.getFullYear() -1
  }

class Date extends Newfunc

new Date('1900-10-10').lastYear()
//expected result: '1899'

Without success, someone can help?

1 answer

7


But in this way I learned in the books that this is not healthy for Compiler, since you are changing the prototype chain natural of javascript.

Where did you read this? Change the prototype of a class can become a problem yes, but because of collisions, not because you are "altering the natural prototype chain", whatever that means.

Change the prototype is a bad idea especially in frameworks, imagine if libraries like jQuery and lodash both implement a method each in the prototype of Array, but each of these methods gives you the arguments in the callback function in different order. Formula for disaster.

This does not mean that it is not possible to create properties for the prototype safely. I would just suggest doing so using the Object.defineProperty because that way the created properties will not be-enumeraveis

Object.defineProperty(Date.prototype, 'lastYear', {
    value() {
        return this.getFullYear() -1
    }
})

Yet if you think it best to extend the class Date, you would need to declare a class extending Date, not declare a class and then try to extend it in Date, That’s not even possible, and if it were, you would fall into the same problem as before.

Example:

class CustomDate extends Date {
  lastYear() {
    return this.getFullYear() -1;
  }
}

var data = new CustomDate();
console.log(data.lastYear());

  • Yeah, I agree with everything you said. I had actually read about not using prototype, but that’s actually what you had said.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.