J
J
JIakki2016-03-07 11:56:25
JavaScript
JIakki, 2016-03-07 11:56:25

Is there an add-on over the constructor so that when a method is called from the prototype, some function is called before that?

For example, there is a constructor and a couple of prototypes:

module.exports = new Quick;

function Quick() {
  this.task = [];
}

Quick.prototype.sync = function() {
  this.task.push('sync')
}

Quick.prototype.js = function() {
  this.task.push('js')
}

Quick.prototype.mocha = function() {
  this.task.push('mocha')
}

And Each method adds the name of itself to the array;
Can I make a function that is called before the visa method (so that bi does not repeat the same code in the methods) ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Shatokhin, 2016-03-07
@JIakki

function Quick() {
  var self = this;
  self.task = [];
  Object.keys(self.constructor.prototype).forEach(function (key) {
    var orig = self.constructor.prototype[key];
    self.constructor.prototype[key] = function () {
      self.task.push(key);
      return orig.apply(self, arguments);
    };
  }; 
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question