For arrow functions, this is picked up from surroundings (lexical).
In other words, Arrow functions are lexically scoped; this means that
their ‘this’ is bound to the context of the surrounding scope
That is to say, whatever ‘this’ refers to can be preserved by using an arrow function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
function Test2() { //this is used as private this.name = "Jabba the Hut"; // this will be bound to the global object. console.log("Test2() Constructor: " + this.name); var age = 36; return { //if we want to use this as public, we have to use self growls : function(phrase) { //NON ARROW FUNCTION // 'name' references the property this.name console.log("Age is: " + age); // can access private variable }, growls2 : function(phrase) { // NON ARROW FUNCTION // this is tied to global, thus, it will use this.name as defined globally // Due to it not being a arrow function, the property this.name // and this.name here, are different. console.log(this.name + " yells out " + phrase); }, growls3 : (phrase) => { // ARROW FUNCTION // correctly uses this to reference the instantiation of this object on the heap // thus, it will use Test2's property this.name console.log(this.name + " yells out " + phrase); } }; } var t2 = new Test2(); //own attribute t2.name = "Ryu.."; t2.growls("hadoken"); t2.growls2("tats makesen bukakyu"); t2.growls3("shoooo ryu ken!"); |
output:
Test2() Constructor: Jabba the Hut
Age is: 36
Ryu.. yells out tats makesen bukakyu
Jabba the Hut yells out shoooo ryu ken!