1

i have the following code . i expected console.log(this.info) to print john in the browser console . but it prints undefined . can someone tell me why ?

const firstObj = {
    info: "john",
    display: function (logger) {
        logger();
    }
}


const secondObj = {
    info: "mike",
    logger: function () {
        console.log(this.info); // logs undefind . but i expected to log john
    }
};


firstObj.display(secondObj.logger);
Soroush
  • 616
  • 5
  • 11
  • You are calling `logger();`, not `something.logger()`. If you were calling `something.logger()` then `this` would be `something`, but there is nothing. – Quentin Sep 06 '18 at 13:44
  • When you pass `secondObj.logger` to the function, you break the relationship with the object. – Pointy Sep 06 '18 at 13:44
  • @Quentin thank you very much . i know how it works now . – Soroush Sep 06 '18 at 13:49

1 Answers1

3

You have to bind the object to specify the context in which this should work:

secondObj.logger.bind(firstObj)

const firstObj = {
    info: "john",
    display: function (logger) {
        logger();
    }
}


const secondObj = {
    info: "mike",
    logger: function () {
        console.log(this.info); // logs undefind . but i expected to log john
    }
};


firstObj.display(secondObj.logger.bind(firstObj));
Mamun
  • 58,653
  • 9
  • 33
  • 46