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
this
keyword in Javascript depends on the context where it is defined. Here is an article explainingthis
keywordIn your example, if you need to get the reference of the object that is returned by
createUser
function, changeuserRef
to a function, something like thisIn order to use
this
you must treatuseRef()
as a function.