Last active
March 15, 2016 01:23
-
-
Save lance/2b2a6a8286b4bb52ddcf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
// Expected output | |
// initial value | |
// Setting 'context.val' set directly | |
// set directly | |
// set directly | |
// Setting 'context.val' using this | |
// using this | |
// using this | |
const context = {}; | |
var val = 'initial value'; | |
Object.defineProperty(context, 'val', { | |
configurable: true, | |
get: () => { | |
return val; | |
}, | |
set: (value) => { | |
console.log("Setting 'context.val'", value); | |
val = value; | |
} | |
}); | |
// Initial value | |
console.log(context.val); | |
// Change context.val directly | |
// We should see console.log from context.val set function | |
context.val = 'set directly'; | |
console.log(context.val); | |
// Even though we `f.call(context)` so that `context` is `this` | |
// in the function body. The `let` declaration hides `this.val`. | |
// Should not see console.log from context.val set function | |
useLet.call(context); | |
console.log(context.val); | |
// Calling `this.val = 'whatever'` from within a function where | |
// `this` is `context` will ensure that `context.val`'s setter is called | |
// We should see console.log from context.val set function | |
useThis.call(context); | |
console.log(context.val); | |
// Calling `var val = 'whatever'` from within a function where | |
// will create a new variable in the function scope. | |
// We should not see console.log from context.val set function | |
useVar.call(context); | |
console.log(context.val); | |
function useLet() { | |
let val = 'using let'; | |
} | |
function useThis() { | |
this.val = 'using this'; | |
} | |
function useVar() { | |
var val = 'using var'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment