5

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.

8
  • function Hammer(object) { this.hit(object); }? Commented Jun 11, 2015 at 18:15
  • But how do I separate it from the constructor function? Commented Jun 11, 2015 at 18:17
  • How would you do it with a raw object? Commented Jun 11, 2015 at 18:17
  • 1
    @dc2, hammer.hit(object); then? Commented Jun 11, 2015 at 18:18
  • Yes - but i'm looking to see if there's a shortcut so I don't have to expose hit. That's the point of this question. If there isn't, well that's why I asked if its possible. :) Commented Jun 11, 2015 at 18:20

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

6 Comments

True, but then could you create two different hammers with different properties? I might want my first hammer to be blue and the other one red!
@dc2 of course; every object returned by the hammer factory is a new one.
Well, that makes you a boss, then.
Eh - in trying this, one side effect is that you can't then access any other functions. How could I do hammer(nail) as well as hammer.clean()? Again jQuery seems to accomplish this.
@dc2 I updated my answer showing how to call hammer.clean. This is the way jQuery does it as well.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.