JSFiddle - React, Tailwind, and code Playground
by jonahe
JavaScript 1.7
class Person {
constructor({name, age}) {
this.name = name;
this.age = age;
}
introduceSelf = () => {
// arrow functions automatically binds 'this'
// 'this' refers to class instance
console.log(`Person says: Hello my name is ${this.name } and I'm ${this.age} year(s) old`);
}
}
const persons = [
new Person({name: "Kalle", age: 30}),
new Person({name: "Kajsa", age: 28}),
new Person({name: "Krister", age: 45})
];
persons.forEach(p => p.introduceSelf());
const test = () => {
// arrow functions automatically binds 'this' to the same as 'this' as the the place where it is declared
// 'this' refers to window object
console.log("testing what this is inside random 'lone' arrow function", this)
}
test();
// can't bind "this" to something else when using a arrow function
console.log("--- trying to bind test function with new 'this'");
test.bind(persons[0])();
const test2 = function() {
console.log("testing what this is inside random function", this);
const testNested = function() {
console.log("Test nested. this : ", this);
}
testNested();
}
test2();
// bind "this" to something else when using a regular function is fine
console.log("--- trying to bind test2 function with new 'this'");
test2.bind(persons[0])();