Skip to content

Instantly share code, notes, and snippets.

View AkashRajvanshi's full-sized avatar
😎
DevOps

Akash Rajvanshi AkashRajvanshi

😎
DevOps
View GitHub Profile
function Person(firstName, lastName) {
this.first_name = firstName
this.last_name = lastName
this.displayName = function () {
console.log(`Name: ${this.first_name} ${this.last_name}`) // Name: Akash Rajvanshi
}
}
let person = new Person("Akash", "Rajvanshi")
const Person = {
firstName: 'Akash',
lastName: 'Rajvanshi',
profession () {
console.log(this) //{ firstName: "Akash", LastName: "Rajvasnhi", profession: f{} }
}
}
Person.profession()
const Person = {
name () {
const firstName = function () {
console.log('Akash', this)
} // window
firstName()
console.log('Rajvanshi', this) // Rajvanshi {name: f}
}
}
const Person = {
name() {
const firstName = _ => console.log('Akash', this) //Akash {name: f}
firstName()
console.log('Rajvanshi', this) //Rajvanshi {name: f}
}
}
Person.name()
const button = document.querySelector('button')
button.addEventListener('click', function () {
console.log(this) // button
})
function foo () {
console.log(this.a) // 3
}
var a = 3 // because this reference the global object and here our var 'a' is global variable.
foo()
function foo() {
console.log(this.a) // 2
}
const obj = {
a: 2,
foo // Es6 syntax of foo: foo
}
obj.foo()
function foo() {
console.log(this.a) //2
}
var obj = {
a: 2
}
foo.call(obj)
// Example with Normal Function
// Value of "this" in this method is overridden to 3
function foo() {
return function (value) {
console.log(this.value) // 3
}
}
var obj1 = {
const firstName = _ => console.log('Akash', this) //Akash -> window
firstName()