Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
Can someone please explain why `this` is different in these two cases
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!