Skip to content

Instantly share code, notes, and snippets.

@sebabelmar
Last active November 27, 2017 18:39
Show Gist options
  • Save sebabelmar/9aa56336cb54f81923b760c1994026ce to your computer and use it in GitHub Desktop.
Save sebabelmar/9aa56336cb54f81923b760c1994026ce to your computer and use it in GitHub Desktop.
ES6 Arrow Functions - this
// ########## ES6 Arrow Functions ################
// ########## this no longer bound ################
// Note: when running the code on an fat-arrow-enabled runtime
// 1.
let aFunc = ()=>{
return this
}
// 2.
let o = {}
o.func = aFunc;
// 3.
let Person = ()=>{
this.func = aFunc;
}
// 4.
class Animal {
constructor(){
this.func = aFunc;
}
}
// Invocations:
// 1.
console.log('this as a function: ', aFunc())
// => this as a function: Window
// 2.
console.log('this as a method: ', o.func())
// => this as a method: Window
// 3.
try {
let person = new Person();
} catch (e) {
console.log(e);
}
// => TypeError: Cannot set property 'func' of Window
// 4.
let animal = new Animal();
console.log('this as class method: ', animal.func())
// => this as class method: Window
// 5. Apply and call do not work either
console.log('this a a given via apply: ', aFunc.apply({banana: 'Love Banana'}))
// => this a a given via apply: Window
console.log('this a a given via call: ',aFunc.call({banana: 'Love Banana'}))
// => this a a given via call: Window
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment