this in JavaScript - aakash14goplani/FullStack GitHub Wiki
-
Explicit binding (using
call()andapply()) takes precedence over implicit binding. Hard binding (usingbind()) takes precedence over explicit binding -
thisworks 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 havethisvariable and value ofthisvariable, 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
thiskeyword is global object
- value of
-
Function Expression
var obj = {}; obj.foo = function() { console.log(this); // {foo: ƒ} } obj.foo();- value of
thiskeyword is referring to object itself
- value of
-
Constructor Function
function foo() { console.log(this); // foo {} } new foo();- value of
thiskeyword is referring to newly created object
- value of
-
Functions using
call()function foo() { console.log(this); } foo.call(...);- value of
thiskeyword is referring to object provided in argument ofcall()method
- value of
-
Arrow functions
const foo = () => { console.log(this); // window } foo();- value of
thiskeyword is referring to the context in which the function is defined
- value of
-
Working of call() and apply() - Explicit Binding
-
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 hasthisvalue set to a new Object i.e.Person {}whereas value ofthisforfullName()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 accessfullNameproperty ofPerson()functionfunction Employee(firstName, lastName) { Person.call(this, firstName, lastName); } new Employee('aakash', 'goplani').fullName(); // aakash goplani- Here
thiswithinPersonwill refer toEmployeeobject and the propertyfullNamewill be invoked withEmployeeobject 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.