//3rd example fat arrow demonstrating "this"
//use a .html page with a <button>Test</button> element
var button = document.querySelector('button');
//fat arrow this maintains the scope of the function
var fn2 = () => {console.log(this)};
//old fashioned functions this refers to object that is calling the function
function fn() {console.log(this)};
button.addEventListener('click',fn2);
// build a class w/a constructor that accepts a name when instantiated
class Person {
constructor(name){
this.name = name;
}
//print name, traditional function call, it redefines "this" scope to the calling function (comes back empty)
printNameFunction(){
setTimeout(function() {
console.log('Function: ' + this.name);
}, 100)
}
//...same exact print fn but uses fat arrow, "this" scope preserved to the method's scope (returns 'Rich')
printNameArrow(){
setTimeout(() => {
console.log('Arrow: ' + this.name);
}, 100)
}
}
let person = new Person('Rich');
person.printNameFunction();
person.printNameArrow();