I am confused about javascript object methods on This and the implementation of ()=> instead of function(){},
Would you care to explain the behaviour of this: thanks
const obj = {
prop : 123,
test : function (){
console.log(this.prop);
},
test2 : ()=>{
console.log(this.prop);
},
}
console.log(test()); //results to 123
console.log(test2()); //results to undefined
thisfrom the parent scope into the new function scope.thiskeyword in JavaScript does not behave like it does in C++, Java or C# - and sometimes it can behave unpredictably for beginners (e.g. in event-listeners).obj.test()andobj.test2()in your example?testandtest2are not define globally so this gives errors.