简体   繁体   中英

Node.js prototypal inheritance

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM