“this” in JS exercise

📄 Table of contents

◉ “this” keyword in js

◉ bind-ing “this"

◉ “this” exercises

var foo = {
name: "anil",
age: 30
};
function getDetails() {
return (this.name + " is + this.age + " yrs old.");
}
foo.logMyDetails = getDetails;
console.log(foo.logMyDetails());
//anil is 30 yrs old.
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
function Employee(name) {
this.name = name;
this.getName = function () {
return this.name;
}
}
var e1 = new Employee(“anil");
e1.getName();
#anil ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
function Employee(name) {
this.name = name;
}
Employee.getName = function () {
return this.name;
}
var e2 = new Employee("kumar");
e2.getName(); #TypeError
var e3 = e2.getName;
console.log(e3()); #TypeError
var e4 = e2.getName.bind(e2);
console.log(e4()); #TypeError
NOTE: if we re-write above getName as `Employee.prototype.getName` then above bind() will work and print "kumar" accordingly.▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬var x = "outermost";
var foo = {
x: "inner",
baz: {
x: "innermost",
bar: function () {
return this.x;
}
}
}
var go = foo.baz.bar; # "this" refers to global object
console.log(go());
console.log(foo.baz.bar())# outermost
# innermost

◉ ‘this’ inside arrow functions

Exercises for the brave

Explanation

◉ What happens to ‘this’ in a function nested inside a method of an object?

◉ `this` inside Classes

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.