-
Notifications
You must be signed in to change notification settings - Fork 1
this in JavaScript
-
Explicit binding (using
call()
andapply()
) takes precedence over implicit binding. Hard binding (usingbind()
) takes precedence over explicit binding -
this
works on the context of execution. Execution context is a concept in the language spec that—in layman's terms—roughly equates to the 'environment' a function executes in; that is, variable scope (and the scope chain, variables in closures from outer scopes), function arguments, and the value of the this object. -
The contents in execution context depends on the way in which method is called. One of the variable/argument of that execution context is
this
. Anytime you write a function, you'll havethis
variable and value ofthis
variable, depends on the way you call a function. -
There are four ways of defining functions:
-
Regular Functions
function foo() { console.log(this); // window reference } foo();
- value of
this
keyword is global object
- value of
-
Function Expression
var obj = {}; obj.foo = function() { console.log(this); // {foo: ƒ} } obj.foo();
- value of
this
keyword is referring to object itself
- value of
-
Constructor Function
function foo() { console.log(this); // foo {} } new foo();
- value of
this
keyword is referring to newly created object
- value of
-
Functions using
call()
function foo() { console.log(this); } foo.call(...);
- value of
this
keyword is referring to object provided in argument ofcall()
method
- value of
-
Arrow functions
const foo = () => { console.log(this); // window } foo();
- value of
this
keyword is referring to the context in which the function is defined
- value of
-
-
I have a person's method that takes two parameters
function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; this.fullName = function() { return this.firstName + ' ' + this.lastName; } } new Person('aakash', 'goplani');
-
In the above example, we have two functions defined viz.
Person()
andfullName()
. Both have different values forthis
. Person hasthis
value set to a new Object i.e.Person {}
whereas value ofthis
forfullName()
is the object on which the the function is called i.e.Person {firstName: "aakash", lastName: "goplani", fullName: ƒ}
-
Now I have
Employee()
function that needs to accessfullName
property ofPerson()
functionfunction Employee(firstName, lastName) { Person.call(this, firstName, lastName); } new Employee('aakash', 'goplani').fullName(); // aakash goplani
- Here
this
withinPerson
will refer toEmployee
object and the propertyfullName
will be invoked withEmployee
object reference.
- Here
-
While the syntax of this function is almost identical to that of
apply()
, the fundamental difference is thatcall()
accepts an argument list, whileapply()
accepts a single array of arguments.