The "This" in JavaScript is pretty confusing and i guess requires a whole POST to describe different scenarios to understand it better.
Basically, "This" is set based on from where the function is called. Eg.
var name = 'Elsa';
function callName() {
console.log("name", this.name)
}
var obj = new callName(); // This would print 'undefined', this would point to window object this.window.name == 'Elsa'
Eg below:
var obj1 = {
name: 'Prem',
func: function() {
console.log(this.name) // this refers to obj1
}
}
obj1.func() // this would print 'Prem'
- So, by default "This" points to the global scope or window scope in a function.
function a() {
console.log(this) // this is global scope, or window scope
}
- In case we make of 'use strict' mode then "This" points to undefined.
Basically, "This" is set based on from where the function is called. Eg.
var name = 'Elsa';
function callName() {
console.log("name", this.name)
}
var obj = new callName(); // This would print 'undefined', this would point to window object this.window.name == 'Elsa'
- Another point to be noted, if we have a method inside an object then "This" points to the object.
Eg below:
var obj1 = {
name: 'Prem',
func: function() {
console.log(this.name) // this refers to obj1
}
}
obj1.func() // this would print 'Prem'
- We can change the scope of this using certain functions like this, using the .call method
var obj1 = {
name: 'Prem',
func: function() {
console.log(this.name) // this refers to obj1
}
}
obj1.func() // this would print 'Prem'
var obj2 = {name: 'Ratan'}
obj1.func.call(obj2); // this would print 'Ratan'
Always make sure to identify the difference between a global variable and local variable even
though the variable name is same.
One last example:
function movie() {
var name = "Prem"; // this is a local variable of movie func
this.maker = "Ratan"; // this points to global scope here
console.log(this.name + " " + maker); // output: undefined Payo
}
var name = "Dhan"; // global variable
var maker = "Payo"; //global variable
obj = new movie(); // This will create an object of function movie()
console.log('maker', obj.maker); // this will print Ratan
In the above example this.name and name are 2 different variables,
similarly this.maker and maker.