Advertisement
danielfajt

Arrow function and .this context

Mar 29th, 2020
602
0
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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement