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);
SoroushNeshat
  • 656
  • 5
  • 11

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
  • 66,969
  • 9
  • 47
  • 59