Predict the output of the following javascript code
const greet = function() {
console.log(this.message);
};
const obj = {
message: 'Hello, world!',
};
const boundGreet = greet.bind(obj);
boundGreet();
Quiz Explanation
This JavaScript code defines a function greet
and an object obj
, then creates a bound function boundGreet
using the bind()
method. Let's break it down:
const greet = function() {
console.log(this.message);
};
- Defines a function named
greet
which logs themessage
property of the object thatthis
refers to.
const obj = {
message: 'Hello, world!',
};
- Creates an object named
obj
with a propertymessage
set to'Hello, world!'
.
const boundGreet = greet.bind(obj);
- Binds the
greet
function to theobj
object using thebind()
method. This means that wheneverboundGreet
is called,this
insidegreet
will refer toobj
.
boundGreet();
- Calls the
boundGreet
function. SinceboundGreet
is bound to theobj
object,this.message
insidegreet
will refer to themessage
property ofobj
. - Therefore, it will log
'Hello, world!'
to the console.
So, the output of this code will be:
Hello, world!