call
and this
in JavaScript
function setUserName(userName) {
console.log('called');
this.userName = userName;
}
function createUser(userName, email, phoneNo) {
setUserName.call(this, userName); // To hold the reference for function we use call property / function
this.email = email;
this.phoneNo = phoneNo;
}
const userOne = new createUser('John', 'john@fb.com', '100');
console.log(userOne);
1. Function Definitions
-
setUserName(userName)
:- Logs
'called'
to the console. - Assigns
userName
tothis.userName
.
- Logs
-
createUser(userName, email, phoneNo)
:- Calls
setUserName.call(this, userName)
to executesetUserName
in the correct context. - Assigns
email
andphoneNo
tothis
.
- Calls
2. Why the Code Works
.call()
for Function Borrowing:- Ensures
setUserName
runs in thecreateUser
object’s context.
- Ensures
new
Keyword Mechanics:- Creates a new object
{}
. - Sets
this
to reference that object insidecreateUser
. - Executes
setUserName.call(this, userName)
, settinguserName
. - Assigns
email
andphoneNo
tothis
. - Returns the newly created object.
- Creates a new object
3. Output
called
createUser { userName: 'John', email: 'john@fb.com', phoneNo: '100' }
4. Trivia
-
Why Not
this.setUserName(userName);
?setUserName
is not a method ofcreateUser
, sothis.setUserName(userName)
would cause an error.
-
Alternative ES6+ Class Implementation
class User {
constructor(userName, email, phoneNo) {
this.setUserName(userName);
this.email = email;
this.phoneNo = phoneNo;
}
setUserName(userName) {
console.log('called');
this.userName = userName;
}
}
const userOne = new User('John', 'john@fb.com', '100');
console.log(userOne); -
.apply()
AlternativesetUserName.call(this, userName);
could also be written as:setUserName.apply(this, [userName]);
-
Arrow Functions Won't Work Here
- Arrow functions do not have their own
this
, so using an arrow function insetUserName
would fail.
- Arrow functions do not have their own