JavaScript Coding Question on this keyword

Here is some JavaScript code and we want to get its output. In this piece of code, you will need an understanding of this keyword in JavaScript and use it in conjunction with apply method available on all functions.

Code

function fill(a,b){
this.a = a;
this.b = b;
console.log(this);
}
let object1 = {c: 'c', d: 'd'}
let object2 = {m: 'm', n: 'n'}
object1.fill = fill;
object2.fill = fill;
object1.fill.apply(object2, ["a1", "b1"])

Full Transcript

00:00 Here's some JavaScript code based on JavaScript this and we want to get its output. There is a function fill() that accepts two arguments a and b. It then assigns two properties a and b to this and then log the value of this. As you can see both the properties are assigned to this. How do I know what this is? Well, this will refer to the caller who will call this function and the caller could be anyone. It could be a global object or any other object. Next we have 2 variables. object1 and object2. They both hold two objects and each object has two properties. Now we add a new property fill to both of these objects and they contain the reference to the fill() function. Finally, this piece of code, calls the fill() method on object1 but it changes its this binding to object2 by calling apply() method.

00:52 This apply() method is available on all functions and its job is to call a function with a given this value, in our case the function it'll call is fill and we pass object2 as this value.

01:05 fill() function also needs 2 arguments that are passed as an array. These two lines of code create object1 and object2. Then we add a property called fill on object1 and object2. The fill property is a reference to the fill() function so when these lines of code are executed both object1 and object2 will have the fill property attached to them. Finally, when fill() function is called on object1 using apply() method. It's this binding is set to object2 and the arguments to fill() function remain as a1 and b1.

01:38 fill() function adds two properties a and b on object2 which is now modified and here is the structure of object2. When we log the value of this, here should be the answer. Let's run the code on the editor and this is the right answer that contains all the properties available on object2. If you would like to take your JavaScript knowledge to the next level and want to know and understand how browsers execute JavaScript and the role of event loop, check out our new course which is live. I've added the link in the description below and friends keep learning and share your knowledge.