Usage of this in Javascript
When you work in JavaScript then this keyword changes the context or scope based on how it is used. So here are some examples of how to use this keyword in JavaScript.
function func_1() {
console.log(this);
}
// calling a function
func_1(); // this pointing to window
// as object method
var myobj = {myfunc: func_1};
myobj.myfunc(); // this pointing to Object
// Use as Constructor
new func_1(); // this pointing to Object that inherits from func_1.prototype
Usages of this when Scope is changed
When your calling scope of this is changed then the best way to assign this in a new variable and use the variable.
function func_2(data, someevent) {
this.data = data;
var self = this;
someevent.on('data', function() {
alert(self.data);
});
}
Bind function with the passing scope of this
function func_3(data, someevent) {
this.data = data;
var internalFunction = (function() {
alert(this.data);
}).bind(this); // Pass this on bind to pass outer scope
someevent.on('data', internalFunction);
}
Use Lambda Function to access scope in ES6
function func_4(data, someevent) {
this.data = data;
someevent.on('data', () => alert(this.data));
}
Call function on the event with the same scope
function callbackFunction() {
console.log(this.data);
}
function func_5() {
this.data = 100,
document.body.onclick = this.callbackFunction.bind(this);
}
Keywords: