-1
let obj = {
    one: function(){
        this.two();
    },

    two: function(){
        console.log("two");
    }
}

let oneFunc = obj.one;

obj.one(); // two

oneFunc(); // TypeError: this.two is not a function

I have been programming in JavaScript for quite some time. I thought I had a really solid grasp on the this keyword. However, I ran in to this today and it blew my mind. I can't figure out why this is happening. When I call oneFunc(), this refers to the global object. Why does this happen?

Lee Morgan
  • 550
  • 1
  • 6
  • 26

1 Answers1

1

this refere to the object, and what you are doing here is creating a function equal to the methode of the object and so you lose the reference to the object.

You can use bind

let obj = {
    one: function(){
        this.two();
    },

    two: function(){
        console.log("two");
    }
}

let oneFunc = obj.one;
oneFunc = oneFunc.bind(obj);

obj.one(); // two

oneFunc(); // TypeError: this.two is not a function
Thibaud
  • 1,059
  • 4
  • 14
  • 27
  • That actually makes a lot of sense. Still seems pretty weir though. I am amazed that I haven't run into this problem before. Thanks. – Lee Morgan Nov 12 '21 at 10:36