chovy
chovy

Reputation: 75774

how to bind a descendant function to the top level parent object?

this.site is undefined in my example.

If I don't use the .bind() it refers to .next (its parent), not the top level object. Is there anyway to get this to always refer to the top level object exports?

var exports = {
    site: site,
    results: {
        next: function($){
            debugger;
            console.log('Site: ', this.site);
            return this.site + $('.foo').attr('href');
        }.bind(exports),
    }
};

module.exports = exports;

Upvotes: 1

Views: 389

Answers (1)

Felix Kling
Felix Kling

Reputation: 816790

You can't use .bind at that moment because the object is still being constructed and exports doesn't have a value yet (or at least not the one you want). You have to bind the function, after you created the object. i.e.

exports.results.next.bind(exports);

Or you restructure your code a bit and make use of the existing exports object:

exports.site = site,
exports.results = {
    next: function($){
        debugger;
        console.log('Site: ', this.site);
        return this.site + $('.foo').attr('href');
    }.bind(exports),
};

Or you simply use exports instead of this, like adeneo mentioned. There is no advantage to use this over exports in your case.

Upvotes: 2

Related Questions