Skip to content

Instantly share code, notes, and snippets.

@rabmarjan
Last active August 25, 2018 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rabmarjan/701b4778991ecdb5d4f42005ddd774e2 to your computer and use it in GitHub Desktop.
Save rabmarjan/701b4778991ecdb5d4f42005ddd774e2 to your computer and use it in GitHub Desktop.
calculateAge(1985);
function calculateAge(year) {
console.log(2016 - year);
console.log(this); //First 'this'
}
var john = {
name: 'John',
yearOfBirth: 1990,
calculateAge: function() {
console.log(this); //Second 'this'
console.log(2016 - this.yearOfBirth);
}
}
john.calculateAge();
// In this case, the first ‘this’ is the window object, and the second ‘this’ is the john object.
var john = {
name: 'John',
yearOfBirth: 1990,
calculateAge: function() {
console.log(this); //First 'this'
console.log(2016 - this.yearOfBirth);
function innerFunction() {
console.log(this); //Second 'this'
}
innerFunction();
}
}
john.calculateAge();
// In this case, the first ‘this’ is the john object, however, the second object is the window object.
//It’s because the second ‘this’ is inside a regular function call.
var john = {
name: 'John',
yearOfBirth: 1990,
calculateAge: function() {
console.log(this);
console.log(2016 - this.yearOfBirth);
}
}
john.calculateAge();
var mike = {
name: 'Mike',
yearOfBirth: 1984
}
mike.calculateAge = john.calculateAge;
// In this case, ‘this’ in calling john.calculateAge() is john object,
// and ‘this’ in calling mike.calculateAge() is mike object.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment