0

In this scenario I get this to be undefined:

function outside(callback){
    callback()
}

var obj = {
    myProperty: 'john',
  
    f1: function() {
        outside(this.f2)
    },
  
    f2: function() {
        console.log('-->', this.myProperty)
    }
}

obj.f1()

How to fix it so this in f2 will refer to obj?

Azevedo
  • 2,059
  • 6
  • 34
  • 52
  • 4
    `f1: function() { outside(this.f2.bind(this)) }` or `f1: function() { outside(_ => this.f2()) }`. See docs for [Function.prototype.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) and [arrow function expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) – Mulan Dec 16 '20 at 17:29

1 Answers1

2

You can use bind for that. See link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Patrick Bender
  • 407
  • 4
  • 16