Skip to content

Instantly share code, notes, and snippets.

@lxynox
Created March 12, 2017 19:48
Show Gist options
  • Save lxynox/f6f5de53f88b323353b661c906749fe4 to your computer and use it in GitHub Desktop.
Save lxynox/f6f5de53f88b323353b661c906749fe4 to your computer and use it in GitHub Desktop.
test JS lexical scope (`fat arrow` vs `function scope`)

Definition

Lexical Scoping defines how variable names are resolved in nested functions: inner functions contain the scope of parent functions even if the parent function has returned.

test function:

function testScope () {
  'use strict'
  console.log('outer [scope]', this)
  
  return function () {
    console.log('inner_fn [scope]', this)
    
    return () => {
      console.log('inner_fat_arrow [scope]', this)
    }
  }
}

global setup:

let foo = { id: 'foo' }
let bar = { id: 'bar' }
foo.test = testScope

test driver:

bar.test = foo.test()
bar.test()
bar.test()()

Conclusion:

  1. fat arrow function auto bind the lexical scope where it's declared
  2. lexical scope resolves to the direct parent where it's declared. (the first inner function in this case)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment