skip to Main Content

I saw this code example online and when I run it it logs nothing on the console. I was expecting it to log "User Name" but its logs nothing. why is that so? Why "this" is not pointing to a newly created object? how JS determines the reference of this. What will be the behavior if I change normal function to arrow function and also if I put comple

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);

2

Answers


  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;
          },
       };
    }
    
    
    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search