0

Revised Question: I came across this code example online, and when I executed it, nothing was logged to the console. I expected it to log "User Name," but it didn't. I'm wondering why this is happening. Why isn't "this" pointing to the newly created object? How does JavaScript determine the reference of "this"? What will happen if I change the normal function to an arrow function, and what if I include a complete condition inside the function?

function createUser() {
      // create an object and return from function
      return {
         name: "User Name", 
         userRef: this,
      };
    }
    // newly create object assigned to user variable 
    var user = createUser();
 
    console.info(user.userRef.name);
Asad Gulzar
  • 403
  • 4
  • 8

2 Answers2

1

this keyword in Javascript depends on the context where it is defined. Here is an article explaining this keyword

In your example, if you need to get the reference of the object that is returned by createUser function, change userRef to a function, something like this

function createUser() {
   return {
      name: "User Name",
      userRef: function() {
        return this;
      },
   };
}

Bharat
  • 74
  • 3
1

In order to use this you must treat useRef() as a function.

function createUser() {
  return {
    name: "User Name",
    useRef(){
      return this;
    },
  };
}

let user = createUser();
   
console.log(user.useRef().name);
udoyhasan
  • 1,527
  • 5
  • 19