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

237
Views
Why is the "this" keyword in this function not giving an error in JavaScript for duplication?

function makeUser() {
  return {
    name: "John",
    ref() {
      return this;
    }
  };
}

let user = makeUser();

alert(user.ref().name);

From what I've learned from thistutorial, they define as the object before dot and since this is the return value of the function, I thought it would be user.

And this tutorial is defining it as the object that is executing the current function.

I think the object that is executing the current function is user. When you replace this by its value it becomes alert(user.user.name);.

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

0

The value of "this" doesn't refer to the name of an object, it refers to the object itself. So there is no "duplication" here, you're just returning an object, which happens to be the same object you started with.

This is perhaps clearer if you separate things out:

function makeUser() {
  // Create an object
  let myObject = {
    name: "John"
  };
  // Create a function which returns that object
  let myFunction = function(){ return myObject; };
  // Store the function on the object
  myObject.ref = myFunction;
  // Return the new object
  return myObject;
}

// Create an object
let user = makeUser();

// Get the name from the object
alert(user.name);

// Call the ref() function, which happens to return the same object
let otherUser = user.ref();
// Get the name again
alert(otherUser.name);

// No matter how many times you call .ref() it will return the same object
alert(user.ref().ref().ref().ref().name);

about 4 years ago · Juan Pablo Isaza Report

0

this refers to a object the function function belongs to or window object if it belongs to no objects. in this case ref() function is returning the owner object for e.g.,

when you call ref() it will return like this

{ name: 'John', ref: [Function: ref] }
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!