JavaScript/C4/this-Keyword-in-JS/English

From Script | Spoken-Tutorial
Revision as of 11:05, 21 June 2021 by Nancyvarkey (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Title of the script: this keyword

Author: Jayesh Katta Ramalingaiah

Domain Reviewer: Ankita Maske

Novice Reviewer: Praveeen S.

Keywords: JavaScript, HTML, this, binding, implicit, explicit, window


Visual Cue
Narration
Slide: Title Hello and welcome to the spoken tutorial on “this keyword in JS”.
Slide:

Learning Objectives

In this tutorial, we will learn about:
  • this keyword and
  • different types of this keyword bindings in JS
Slide: System Specifications This tutorial is recorded using:
  • Ubuntu Linux OS version 18.04
  • Visual Studio Code version 1.45.0 (code editor)
  • Firefox web browser

However, you may use any other browser of your choice.

Slide: Pre-requisites To practice this tutorial,
  • You should be familiar with writing and executing JS files.
  • If not, please go through the prerequisite tutorials on this website.
Slide: Code files
  • The files used in this tutorial are available in the Code files link on this tutorial page.
  • Pls download and extract the files.
  • Make a copy and then use them for practising.
Slide: ‘this’ keyword in JS
  • Technically, this is an Object.
  • this keyword - refers to the context
  • this keyword can be a global object, function, class or variable.
Slide: ‘this’ keyword in JS


this keyword depends upon binding.
  • Window Binding
  • Implicit Binding
  • Explicit Binding
  • New Binding
Slide: ‘this’ keyword in JS


Explicit Binding has 3 methods:
  • Call
  • Apply
  • bind

Now, let us take an example for each of those and understand them better.

Show VS editor Open Visual Studio Code editor
[Editor] Welcome Page -> Open Folder -> Practice-JS -> index.html & main.js


Then open the files index.html and main.js as explained in the earlier tutorials.


For this demonstration, I have already opened the same.


These files are available in the Code files link for practice.

[Editor] Type:


<!DOCTYPE html>

<html lang="en">

<head>

<title>'this' Keyword</title>

</head>

<body>

<script src="main.js"></script>

</body>

</html>

In the index.html file, replace the code as shown.



Press: Ctrl + S


Press: Alt + L and Alt + O

Save the file and Start the Live server.
[Firefox] Press Ctrl + Shift + I


Point to the browser developer tools


Click on the Console tab

In the web browser, open the Browser developer tools panel and go to the console tab.
Switch to Editor Switch back to the editor.
[Editor] Type:

console.log(this);

In the main.js file, replace the code as shown.
[Editor] Highlight:


console.log(this);

Here, this refers to a global object.


And we are logging ‘this’ in the global scope.

Press: Ctrl + S

Switch to Browser

Save the file and switch back to the browser.
[Browser] [Console Tab]:

Highlight:


Window

If you see here, ‘this’ keyword refers to a Window object.


Technically, a global object is called a Window object.


This type of binding is called Window Binding.

Switch to Editor Switch back to the editor.
[Editor] Type:


var name = "Spoken Tutorials!";

console.log(this.name);

In the main.js file, replace the code as shown.
[Editor] Highlight:


var name = "Spoken Tutorials!";

Here, I have declared a variable with the var keyword.


I have assigned the value Spoken Tutorials to it.

[Editor] Highlight:


console.log(this.name);

Here, with log this.name I’m logging the value on the console.
Press: Ctrl + S

Switch to Browser

Save the file and switch back to the browser.
[Browser] [Console Tab]:

Highlight:


Spoken Tutorials!

In the console, we see Spoken Tutorials being displayed.


As ‘this’ refers to a global object, the Window object contains everything in the browser window.


The ‘name’ variable is also a part of the Window object.


So, this.name refers to Spoken Tutorials.

Only Narration Next, let's learn about implicit binding.



[Editor] Type:


const empDetails = {

name: "Jayesh",

designation: "Instructor",

displayName: function () {

console.log(this.name); },

};


empDetails.displayName();

In the main.js file, replace the code as shown.
[Editor] Highlight:


const empDetails = {

name: "Jayesh",

designation: "Instructor",

displayName: function () {

console.log(this.name);

},

};

Here, I have declared a variable empDetails and assigned an object to it.


The object contains name, designation and displayName properties.

[Editor] Highlight:

displayName: function ()

The displayName property has an anonymous function.
[Editor] Highlight:

console.log(this.name);

I log this.name inside the function.


In the console, we will see what this.name refers to.

[Editor] Highlight:


empDetails.displayName();

Here, I’m making a normal function call to execute the anonymous function.
Press: Ctrl + S

Switch to Browser

Save the file and switch back to the browser.
[Browser] [Console Tab]:

Highlight:


Jayesh

In the console, we can see that this.name value is Jayesh.


name is the property in the object.


So, this refers to the empDetails object.

Switch to Editor Switch back to the editor.
[Editor] Highlight:

empDetails.displayName();

Observe this carefully.

In implicit binding, this refers to the variable before the period(.) in the function call.


So, here we have empDetails variable to which 'this' is being bound to.

Only Narration Next, let’s learn about explicit binding.
[Editor] Type:


const lang = ["HTML", "CSS", "JS"];


const empDetails = {

name: "Jayesh",

};


function display(languages) { console.log(`${this.name} knows ${languages}`);

}


display.call(empDetails, lang);

display.call(empDetails, lang[0], lang[1], lang[2]);

In the main.js file, replace the code as shown.
[Editor] Highlight:


const lang = ["HTML", "CSS", "JS"];

A variable named lang is declared and assigned a string array.
[Editor] Highlight:


const empDetails = {

name: "Jayesh",

};

Then I have declared a variable empDetails and assigned an object to it.


The object has a property called name.

[Editor] Highlight:


function display(languages) {

console.log(`${this.name} knows ${languages}`);

}

Here, I’m declaring a function called display which accepts one parameter that is languages.


Inside the function, I log this.name and languages.

Only Narration The scenario here is to execute the display function having empDetails as a context.


Here ‘this’ should refer to empDetails.

[Editor] Highlight:


display.call(empDetails, lang);

To achieve this, we will learn about the call method in explicit binding.


Here, the call accepts any number of parameters.


The first parameter is the context to which 'this' keyword refers to.


So, we are executing the display function using a call method.


And passing our required context as a first parameter.


The second parameter is the one that the display function accepts.

[Editor] Highlight:


display.call(empDetails, lang[0], lang[1], lang[2]);

Here, I’m using the same call method and passing the array elements separately.


We have a reason for doing this.


We shall compare this while learning the ‘apply’ method in explicit binding.


Press: Ctrl + S

Switch to Browser

Save the file and switch back to the browser.'
[Browser] [Console Tab]:

Highlight:


Jayesh knows HTML,CSS,JS

Here, observe the log carefully.


We can verify that in the call method, the first parameter is the context to which this refers.


That’s the reason we see this.name is printed as Jayesh.


HTML, CSS and JS are from the array as we have passed the array.

[Browser] [Console Tab]:

Highlight:


Jayesh knows HTML

Similarly, observe here that only the first parameter is taken as languages.


The rest of the parameters which are passed are ignored.

This is because the display function accepts only one parameter.

Only Narration Next let’s learn about the ‘bind’ method.
[Editor] Type:


const lang = ["HTML", "CSS", "JS"];


const empDetails = {

name: "Jayesh",

};


function display(languages) {

console.log(`${this.name} knows ${languages}`);

}


const returnedFn = display.bind(empDetails, lang);

console.log(returnedFn);

returnedFn();

In the main.js file, replace the code as shown.
Only Narration Bind is similar to the call method, with a small change.
[Editor] Highlight:


const lang = ["HTML", "CSS", "JS"];


const empDetails = {

name: "Jayesh",

};


function display(languages) {

console.log(`${this.name} knows ${languages}`);

}

I’m using the same variables and the function which were used while explaining the call method.


The scenario is also the same.

[Editor] Highlight:


const returnedFn = display.bind(empDetails, lang);

Here, in the bind method, the first parameter is the context, which this refers to.


The second parameter is the one that the display function accepts.


Here, the bind method returns a function which I’m storing in the returnedFn variable.


I can execute the returnedFn variable anywhere in the program later.

[Editor] Highlight:

console.log(returnedFn);

Just to verify what is being returned, I have put a log here.
[Editor] Highlight:

returnedFn();

Then, I’m just executing the returnedFn.


Press: Ctrl + S

Switch to Browser

Save the file and switch to the browser.
[Browser] [Console Tab]:

function display()

Here, we can verify that the bind method returns the function which can be executed anywhere.
[Browser] [Console Tab]:

Highlight:


Jayesh knows HTML,CSS,JS

On execution of the returned function, we get a similar output that the call method displays.
Only Narration By now, we have understood call and bind methods in explicit binding.


Next, let’s learn about the apply method.

[Editor] Type:


const lang = ["HTML", "CSS", "JS"];


const empDetails = {

name: "Jayesh!",

};


function display(lan1, lan2, lan3) {

console.log(`${this.name} knows ${lan1}, ${lan2} and ${lan3}`);

}


display.apply(empDetails, lang);

In the main.js file, replace the code as shown.
[Editor] Highlight:


const lang = ["HTML", "CSS", "JS"];


const empDetails = {

name: "Jayesh",

};

Similar to the previous example, I have declared two variables, lang and empDetails.
[Editor] Highlight:


function display(lan1, lan2, lan3) {

console.log(`${this.name} knows ${lan1}, ${lan2} and ${lan3}`);

}

Here, in the display function, I’m passing 3 parameters and logging their values.


Recall in the previous example, I had passed only one parameter.

[Editor] Highlight:


display.apply(empDetails, lang);

Here, I’m using the apply method and the scenario is the same.


This will execute the display function having empDetails as context.


Like the call method, even in the apply method, the first parameter is the context to which this refers.


And the second parameter is what the display function accepts as a parameter.

Press: Ctrl + S

Switch to Browser

Save the file and switch to the browser.
[Browser] [Console Tab]:

Highlight:


Jayesh knows HTML, CSS and JS

Here, observe the log carefully.


We can verify that the apply method is similar to the call method.


The first parameter being passed is the context to which this refers.


That’s the reason we see this.name is printed as Jayesh.


HTML, CSS and JS are from the array because we have passed the array as a parameter.

Switch to Editor Switch back to the editor.
[Editor] Highlight:


function display(lan1, lan2, lan3) {

console.log(`${this.name} knows ${lan1}, ${lan2} and ${lan3}`);

}

If you notice this closely, the display function has multiple parameters.


Whereas we pass only one array parameter in the apply method along with the context.


So here, each element in the array is taken as a separate variable.


For example lang1, lang2 and lang3 respectively.

Only Narration This is the main difference between call and apply.


So that’s the reason I have been comparing ‘call’ and ‘apply’ in the demonstrated example.


Next, let’s learn about new binding.

[Editor] Type:


function Student(name) {

this.stuName = name;

}


const s1 = new Student("Jayesh"); console.log(s1);

In the main.js file, replace the code as shown.
[Editor] Highlight:


function Student(name) {

this.stuName = name;

}

When you see this, you might be able to recollect the constructor function.


This was covered while learning about functions.


Here, I have declared a Student function accepting the name parameter.

[Editor] Highlight:


this.stuName = name;

Inside the function, I’ve created a property with the name stuName.


Then I have assigned the passed name parameter to it.

[Editor] Highlight:


const s1 = new Student("Jayesh");

Here, I’m making the function call using new keyword, passing Jayesh as a parameter.


When I pass new keyword, ‘this’ refers to a new context and returns an object.


The returned object is stored in the s1 variable.

[Editor] Highlight:


console.log(s1);

To verify, I’m logging s1 in the console.


Press: Ctrl + S

Switch to Browser

Save the file and switch back to the browser.
[Browser] [Console Tab]:

Highlight:


Object { stuName: "Jayesh" }

In the console, we can see that the function has created a new object with property stuName.


Here, ‘this’ refers to the new context because we are using new keyword.


This is called the new binding.

Only Narration With this, we have come to the end of this tutorial.


Let’s summarize.

Slide: Summary In this tutorial, we have learnt:
  • ‘this’ keyword and
  • Different types of this keyword bindings in JS
Slide: Assignment As an assignment:
  • Open the file assignment.js which you have created earlier.
  • Clear the existing code.
  • Create a student object.
  • The student object should have name, department and displayName as object keys.
Slide: Assignment
  • Assign valid values to name and department keys
  • Assign an anonymous function to displayName key
  • The anonymous function should log the name value in the object using this context
  • Execute the displayName function
Slide: Assignment
  • Open the file MyPage.html in a web browser.
  • Observe the output in the browser’s console
  • Guess which binding this assignment refers to.
Slide: About Spoken Tutorial Project
  • The video at the following link summarises the Spoken Tutorial project.
  • Please download and watch it
Slide: Spoken tutorial workshops
  • We conduct workshops using spoken tutorials and give certificates.
  • For more details, please write to us.
Slide: Forum questions Pls post your timed queries in this forum
Slide: Acknowledgement Spoken Tutorial Project is funded by the Ministry of Education (MoE), Government of India
Slide: Thanks The script for this tutorial is contributed by Jayesh and this is Praveen signing off. Thank you for joining

Contributors and Content Editors

Kr.jayesh, Nancyvarkey, Pravin1389