Clone a native javascript constructor without changing the original

Asked

Viewed 49 times

1

I’m trying to create a personal library, where the original idea was to extend native javascript objects with various useful functions. After reading a little, I ended up convincing myself that extending native objects is not exactly a good idea, so I came up with the idea of creating new constructors exactly like the native constructors, and then adding the methods to them, so as not to affect the originals. The idea would be something like this:

var MyDate = Date;
MyDate.prototype.teste = function() {
    console.log('teste');
};

var a = new MyDate();
var b = new Date();

It works well, only the problem is...

a.teste() // 'teste'
b.teste() // 'teste'

I understood that this occurs because in fact MyDate became just a reference to Date, and not a new constructor, but in this case, how can I "clone" a constructor completely?

1 answer

2


If you want to extend the native javascript classes you should take a look at the keywords class and extends and the concept of class Expression.

   //Extende a classe Date sem interferir com a classe base
   class MyDate extends Date {
      constructor() {
         super(); 
      }    

      // Adiciona um método na declaração de classe
      foo() {
         console.log('Método foo!');
      }

    }

    // adiciona o método teste via protótipo como no exemplo.
    MyDate.prototype.teste = function() {
     console.log('teste');
    };

    var aDate = new MyDate(); 
    var bDate = new Date(); 
    aDate.teste(); // > "teste"
    aDate.foo(); // > "Método foo!"
    bDate.teste(); // > Error: bDate.teste is not a function
    bDate.foo(); // > Error: bDate.foo is not a function

Browser other questions tagged

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