G2A Many GEOs
SHARE
TWEET

Arrow function and .this context

danielfajt Mar 29th, 2020 (edited) 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. console.log('Global this', this)
  2.  
  3. personA = {
  4.   'name': 'Stella',
  5.   'yob': 1986,
  6.   'age1': function() {
  7.     console.log('Age1 is:', 2020 - this.yob)
  8.   },
  9.   'age2': () => {console.log('Age2 is:', this.yob)}
  10. }
  11.  
  12. personA.age1() // output: 34s
  13. personA.age2() // output: undefined
  14.  
  15. function personB() {
  16.   this.name = 'Thomas'
  17.   this.yob = 1991
  18.  
  19.   this.age3 = function() {console.log('Age3 is:', 2020 - this.yob)}
  20.  
  21.   this.age4 = () => {console.log('Age4 is:', 2020 - this.yob)}
  22. }
  23.  
  24. personX = new personB()
  25. personX.age3() // output: 29
  26. personX.age4() // output: 29
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top