Select Sidearea

Populate the sidearea with useful widgets. It’s simple to add images, categories, latest post, social media icon links, tag clouds, and more.

[email protected]

Functions and “this”

Functions and “this”

There are multiple ways “this” is bound in a function. It depends on how function is called:

1. Constructor function
var student = function(name, stu_class, score) { = name;
this.stu_class = stu_class;
this.score = score;

var uniStudent = new student(“Smith”, “B.Tech.”, “8.8”);  // It should log student object.

2. Strict mode in function
function add20(a) {‘use strict’; console.log(this); return a + 20;}

add20(100); // It should log undefined.

3. Function without strict mode
function add100(a) { console.log(this); return a+100; }

add100(200); // It should log window object in browser.

4. Function as object method 
var sportStar = {name: “Sachin Tendulkar”, getName: function() {console.log(this); return;} }
sportStar.getName(); // It should log sportStar object.

However, an arrow function does not have its own this. The this value of the enclosing lexical scope is used.

No Comments

Post a Comment