Skip to content

Instantly share code, notes, and snippets.

View functionDefined.js
const user = {
name: "Ahmar",
keys: [1, 2, 3],
printName: function() {
this.keys.forEach(function(x) {
console.log(this.name);
}, this)
}
}
View arrowUndefined.js
const user = {
name: "Ahmar",
keys: [1, 2, 3],
printName: function() {
this.keys.forEach(function(x) {
console.log(this.name);
})
}
}
View arrowDefined.js
const user = {
name: "Ahmar",
keys: [1, 2, 3],
printName: function() {
this.keys.forEach((x) => {
console.log(this.name);
})
}
}
View arrowFunctions.js
const user = {
name: "Ahmar",
printName: () => {
console.log(this.name);
}
}
user.printName(); //Outputs: Undefined
View class.js
class User {
constructor(name) {
this.name = name;
}
printName() {
console.log(this.name);
}
}
View bind.js
const user = {
name: "Ahmar",
printName: function() {
console.log(this.name);
}
}
const printNameOutsideOfObject = user.printName
const boundFunction = printNameOutsideOfObject.bind(user);
boundFunction(); //Outputs: Ahmar
View printNameOutsideOfObject.js
const printNameOutsideOfObject = function() {
console.log(this.name);
}
printNameOutsideOfObject(); //The "this" here refers to the global window object, and not the user object.
View objectFunction.js
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 Jul 16, 2019
Javascript Object
View printName.js
const user = {
name: "Ahmar",
printName: function() {
console.log(this.name);
}
}
user.printName(); //Outputs: "Ahmar"
You can’t perform that action at this time.