Skip to content

Commit

Permalink
Learned about this keyword in all context and arrow function
Browse files Browse the repository at this point in the history
  • Loading branch information
sohail019 committed Jul 29, 2024
1 parent 725b232 commit af52e4d
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
55 changes: 55 additions & 0 deletions 03 - Chai aur Javascript/14 - this Keyword/01_this.js
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 03 - Chai aur Javascript/14 - this Keyword/02_arrow_function.js
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

0 comments on commit af52e4d

Please sign in to comment.