Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created September 6, 2018 17:14
Show Gist options
  • Save prof3ssorSt3v3/a42ee8ba1cad64e08a503df43a4a8dc0 to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/a42ee8ba1cad64e08a503df43a4a8dc0 to your computer and use it in GitHub Desktop.
const obj = {
prop1: 'hello',
things: ['hammer', 'sickle', 'lollipop'],
f1: function(msg){
//`this` will refer to obj because obj called f1
this.things.forEach( function(thing){
console.log(msg, thing);
console.log(this.prop1);
//inner this points to window/global obj
})
console.log('\n\n');
},
f2: (msg)=>{
//fails because arrow function looks at `this` when code is written
//which means global/window object, which has no `things`
if( this.things ){
this.things.forEach( function(thing){
console.log(msg, thing);
console.log(this.prop1);
});
}
console.log('\n\n');
},
f3(msg){
//works the same as f1
//this will refer to obj because obj called f3
this.things.forEach( function(thing){
console.log(msg, thing);
console.log(this.prop1);
//inner this points to window/global obj
})
console.log('\n\n');
},
f4(msg){
//works the same as f1 and f3
//this will refer to obj because obj called f4
this.things.forEach( function(thing){
console.log(msg, thing);
console.log(this.prop1);
//inner this points to obj because of optional forEach context param
}, this);
//optional parameter to pass in the context, which will be `obj` here
console.log('\n\n');
},
f5(msg){
//works the same as f1 and f3
//this will refer to obj because obj called f4
this.things.forEach( thing => {
//`this` looks at its surrounding context (lexical scope) only
console.log(msg, thing);
console.log(this.prop1);
});
//called without the optional context. Doesn't matter.
this.things.forEach( thing => {
//`this` looks at its surrounding context (lexical scope) only
console.log(msg, thing);
console.log(this.prop1);
}, this);
//optional parameter to pass in the context. Doesn't matter.
console.log('\n\n');
}
}
obj.f1('f1 normal function.');
obj.f2('f2 arrow function.');
obj.f3('f3 shorthand method.');
obj.f4('f4 shorthand method.');
obj.f5('f5 shorthand method.');
obj.f2.call(obj, 'f2 part 2 with call. THIS: ');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment