-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Learned about this keyword in all context and arrow function
- Loading branch information
Showing
2 changed files
with
71 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
// this Keyword | ||
// 'use strict' | ||
|
||
// Global Context | ||
console.log(this) // Output: {} in node and window object in browser. | ||
|
||
// ---------------------------------------- | ||
// Function Context | ||
function show(){ | ||
console.log(this); | ||
} | ||
|
||
show() // Global object ko refer karta hai | ||
|
||
// Function context in strict mode | ||
// function showInStrict(){ | ||
// console.log(this); | ||
// } | ||
|
||
// showInStrict() // undefined | ||
|
||
// ------------------------------------------------ | ||
// Method Context | ||
|
||
const person = { | ||
name: 'Sohail', | ||
age: 21, | ||
greet: function(){ | ||
console.log(`Hello ${this.name}`); | ||
} | ||
} | ||
|
||
person.greet() // Output: Hello Sohail | ||
|
||
// ------------------------------------------------ | ||
// Constructor Context | ||
|
||
function Car(brand, model){ | ||
this.brand = brand | ||
this.model = model | ||
} | ||
|
||
const myCar = new Car("Tata", "Safari") | ||
console.log(myCar.brand); // Tata | ||
console.log(myCar.model); // Safari | ||
|
||
// ------------------------------------------------ | ||
// Event Handlers | ||
const myBtn = document.querySelector('#myBtn') | ||
|
||
myBtn.addEventListener('click', function(){ | ||
console.log(this); // this refers to the button element | ||
}) | ||
|
||
|
16 changes: 16 additions & 0 deletions
16
03 - Chai aur Javascript/14 - this Keyword/02_arrow_function.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
// Arrow Function with this | ||
|
||
const obj = { | ||
name: 'Sohail', | ||
regularFunction: function(){ | ||
console.log(this.name); | ||
}, | ||
|
||
arrowFunction: () => { | ||
console.log(this.name); | ||
} | ||
} | ||
|
||
console.log(obj.name) // Sohail | ||
obj.regularFunction() // Sohail | ||
obj.arrowFunction() // undefined |