Skip to content

Instantly share code, notes, and snippets.

const user = {
name: "Ahmar",
keys: [1, 2, 3],
printName: function() {
this.keys.forEach(function(x) {
console.log(this.name);
}, this)
}
}
const user = {
name: "Ahmar",
keys: [1, 2, 3],
printName: function() {
this.keys.forEach(function(x) {
console.log(this.name);
})
}
}
const user = {
name: "Ahmar",
keys: [1, 2, 3],
printName: function() {
this.keys.forEach((x) => {
console.log(this.name);
})
}
}
const user = {
name: "Ahmar",
printName: () => {
console.log(this.name);
}
}
user.printName(); //Outputs: Undefined
class User {
constructor(name) {
this.name = name;
}
printName() {
console.log(this.name);
}
}
const user = {
name: "Ahmar",
printName: function() {
console.log(this.name);
}
}
const printNameOutsideOfObject = user.printName
const boundFunction = printNameOutsideOfObject.bind(user);
boundFunction(); //Outputs: Ahmar
const printNameOutsideOfObject = function() {
console.log(this.name);
}
printNameOutsideOfObject(); //The "this" here refers to the global window object, and not the user object.
const user = {
name: "Ahmar",
printName: function() {
console.log(this.name);
}
}
const printNameOutsideOfObject = user.printName
printNameOutsideOfObject(); //Error, cannot read property of undefined.
@ahmarsuhail
ahmarsuhail / printName.js
Last active July 16, 2019 17:49
Javascript Object
const user = {
name: "Ahmar",
printName: function() {
console.log(this.name);
}
}
user.printName(); //Outputs: "Ahmar"