Last active
August 25, 2018 18:13
-
-
Save rabmarjan/701b4778991ecdb5d4f42005ddd774e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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