Interview Question - JavaScript this keyword in object
This is an interview question on JavaScript Objects and this
keyword.
Code
"use strict"let value = {a: 10,f: function(){console.log(this.a);}}let object1 = {a:20, linked: object2};let object2 = {a:40, linked: value};value.f.call('value', object2);
Full Transcript
In this question, we are running the code in the strict
mode. We have an object called value
, which has one property called a
and a method called f
.
This method f
is written using function declaration and its implementation contains one line, which prints the value of this.a
.
We create two objects, object1
and object2
, with few properties. And finally we execute the method called call
on the method f
of the value
object.
Let's work together to find the right answer. In this question we first create a value
object. Then in the next line, we create object1
, which has two properties, a
,
which has the value of 20
and linked
, which is referring to another object called object2
. However, the object2
variable is declared after it is used.
Also object2
is declared using the let
keyword, which means the variable declaration is not hoisted
. And therefore using the variable before it is declared is not allowed.
Therefore executing this code will result in ReferenceError
, which is the correct answer. Let's run the code in IDE to prove that.
We are in IDE and as we go and hit run, we can see that ReferenceError
object2
is not defined, has appeared as the correct output.