|
| 1 | +/* |
| 2 | +this keyword reference the object that is executing the current function |
| 3 | +
|
| 4 | +If that function is part of na object we call that function a method. |
| 5 | +method ---> this references that object itself |
| 6 | +
|
| 7 | +If that function is a regular function, not part of an object. |
| 8 | +function ---> this references the global object (which is the window object in browsers and global in node) |
| 9 | +
|
| 10 | +constructor function ---> 'this' references to new object |
| 11 | +*/ |
| 12 | + |
| 13 | +// CASE 1 (IN OBJECT METHOD) |
| 14 | +// As read is a method of people object, 'this' keyword refers to person object itself. |
| 15 | +const people = { |
| 16 | + fname: "Aashish", |
| 17 | + id: 2, |
| 18 | + read() { |
| 19 | + console.log(this) |
| 20 | + } |
| 21 | +} |
| 22 | +people.read(); |
| 23 | + |
| 24 | +// CASE 2 (IN BARE/DEFAULT FUNCTION) |
| 25 | +// Here,'this' keyword refers to global object which is windows in browser and global in node |
| 26 | +function eat() { |
| 27 | + console.log(this); |
| 28 | +} |
| 29 | +eat(); |
| 30 | + |
| 31 | +// CASE 3 (IN CONSTRUCTOR FUNCTION) |
| 32 | +// Here, 'this' keyword refers to new Student object |
| 33 | +function Student(school, roll) { |
| 34 | + this.school = school; |
| 35 | + this.roll = roll; |
| 36 | + console.log(this); |
| 37 | +} |
| 38 | + |
| 39 | +const aashish = new Student("JMC", 1); |
| 40 | + |
| 41 | +const video2 = { |
| 42 | + title: "a", |
| 43 | + tags: ["a", "b", "c"], |
| 44 | + play() { |
| 45 | + // Here 'this' references the object itself, because play is a method in the video object. |
| 46 | + console.log(this); |
| 47 | + }, |
| 48 | + showTags() { |
| 49 | + // If we use a function as a callback function, It will be treated as default/bare function |
| 50 | + // so that 'this' keyword references the global object. |
| 51 | + this.tags.forEach(function (tag) { |
| 52 | + console.log(this.title, tag); |
| 53 | + }, this); // As a second argument we can pass this keyword. So the 'this' in the callback function references the object itself and not the global object. |
| 54 | + }, |
| 55 | +}; |
| 56 | + |
| 57 | +video2.showTags(); |
0 commit comments