Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS run function from constructor after object instantiation

Tags:

javascript

Is it possible to do this:

var hammer = new Hammer(); // create a new instance
hammer(nail); // really call Hammer.prototoype.hit(object);

I can figure it out on a raw object, but not when creating a new instance of an object. This is what I am running into:

function Hammer(options) {
  this.config = options.blah;
  this.hit(/* ? */);
  return this;
}

Hammer.prototype.hit = function(obj) {
  // ...
}

When I call the constructor, I want to pass in special options - not what nail to hit. However, when I call it later, I want to pass in a nail. I'm missing something.

like image 317
dthree Avatar asked Sep 27 '22 15:09

dthree


1 Answers

One solution is to not create a constructor function at all:

var hammer = newHammer();

hammer(nail);

hammer.clean();

function newHammer(options) {
    var config = options.blah;

    hit.clean = clean;

    return hit;

    function hit(obj) {
        // ...
    }

    function clean() {
        // ...
    }
}

To me, this is a much cleaner solution than messing around with constructors and prototypes.

like image 52
Aadit M Shah Avatar answered Oct 06 '22 18:10

Aadit M Shah