JS this
by Gustavo
JavaScript
var obj = { a: 'object' };
var a = 'global';
var showName = function() {
console.log('function', this.a);
}
var showNameArrow = () => console.log('arrow', this.a);
obj.showName = showName;
obj.showNameArrow = showNameArrow;
showName(); // "function", "global"
showNameArrow(); // "arrow", "global"
obj.showName(); // "function", "object"
obj.showNameArrow(); // "arrow", "global"
/*** Nested ***/
var nested = {
a: 'object',
method() {
// "use strict";
function show() { console.log('nested', this.a) }
show();
}
};
nested.method(); // "nested", "global" (undefinded error in strict mode)
/*** In a setTimeout ****/
var obj2 = {
a: 'banana',
b: 'apple',
method: function(number) {
const self = this;
// regular function
var callback = function() {
console.log(this.a, this.b, self.b, number);
}
setTimeout(callback, 1);
setTimeout(callback.bind(this), 1);
},
methodArrow: function(number) {
// arrow function
callback = () => console.log(this.a, this.b, number);
setTimeout(callback, 1);
},
executeCallback: function(callback) {
callback();
}
}
const myCallback = () => { console.log(this.a) };
obj2.method(10); // "global", undefined, "apple", 10
// "banana", "apple", "apple", 10 (using bind)
obj2.methodArrow(10); // "banana", "apple", 10
obj2.executeCallback(myCallback); // "global"