1

Trying to wrap my mind around prototypes in Javascript, specifically Node.js, with a simple test.

function Lint() {
    this.input = 'foo';
    events.EventEmitter.call(this);
}

Lint.prototype.dirs = function (dirs) {
    _.each(dirs, this.files);
}

Lint.prototype.files = function (dir) {
    console.log(this.input); // trying to get 'foo', returns undefined
}

var lint = new Lint();

lint.dirs(['js', 'js/views']);

Lint.prototype.files logs undefined because this isn't referring to the instance of Lint. What am I missing here?

The only solution I can think of, that works, is passing around the initial this from Lint.prototype.dirs to each other function. I'm pretty sure there's a better way.

1 Answer 1

4

this refers to the lint object, but you're not passing the Lint object to _.each. You're detaching the function from the object and passing that.

You can bind the context of a function to the desired value using Function.prototype.bind...

_.each(dirs, this.files.bind(this));

Or, you could keep a reference to the this value, and pass an anonymous function to _.each...

var this_lint = this;

_.each(dirs, function(v) {
    this_lint.files(v);
}
Sign up to request clarification or add additional context in comments.

3 Comments

@alex: That's my thing now. All my answers are CW, so feel free to pitch in if you'd like. ;-)
Thanks so much! Interestingly enough, why does this variation return false? var this_lint = this; _.each(dirs, this_lint.files);
@wayne: In that case, you're really doing the same thing as you were in your original code. You're just passing the .files function to the _.each. The this_lint does not stay with the function when you pass it. That's where .bind is handy. It creates a new function with the first argument given to .bind set as the this value of the new function.

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.