this keyword

This fiddle has a few examples of this keyword being used in

by Saksham Malhotra

JavaScript

/*function outer() {
  var x = 5;

  function inner() {
    console.log(this == window); //undefined as this refers to the scope in which the function is executed which is global
  }

  inner();
}
outer();*/



/*function outer() {
	var x = 5;
	function inner() {
   console.log(this == window);//undefined as this refers to the scope in which the function is executed which is again global
  }
  return inner
}
var func = outer();
func();*/


/*function outer() {
	x = 5;//var keyword is missing so a global variable is created
	function inner() {
   console.log(this.x);//5 as this refers to the scope in which the function is executed which is global
  }
  return inner;
}
var func = outer();
func();*/

/*var x = 6;

function outer() {
  var x = 5;

  function inner() {
    console.log(this.x); //6 as this refers to the scope in which the function is executed which is global
  }
  inner();
}
outer();
*/


/*var person = {
	fname: 'saksham',
  age: 29,
  greet: function() {
  	var sayHi = function() {
    	console.log('Hi, I am ' + this.fname);
    }
    sayHi();
  }
}
//this would print undefined ans sayHi creates its own reference to `this` which points to the scope it is executed in; global
person.greet();*/


/*var person = {
	fname: 'saksham',
  age: 29,
  greet: function() {
  	var sayHi = () => {
    	console.log('Hi, I am ' + this.fname);
    }
    sayHi();
  }
}
//this prints saksham as arrow functions creates a reference to `this` which points to the parent scope which is an object.
person.greet();*/


/*var obj = {
    age:29,
    getAge: function() {
        var age = 30;
		var againGetAge = function(){
			console.log(this.age + ' ' + age);
        }
		againGetAge();
    }
}
var age = 55;
obj.getAge();*/





/*var obj = {
    age:29,
    getAge: function() {
        var age = 30;
		var againGetAge = () => {
			console.log(this.age + ' ' + age);
        }
		againGetAge();
    }
}

obj.getAge();*/