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) {
this.name = name;
this.stu_class = stu_class;
this.score = score;
console.log(this)}
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 this.name;} }
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.