Skip to content

Instantly share code, notes, and snippets.

@hafeez-syed
Last active January 18, 2017 06:02
Show Gist options
  • Save hafeez-syed/5bf11f729c736beee10cd5fa8f898a98 to your computer and use it in GitHub Desktop.
Save hafeez-syed/5bf11f729c736beee10cd5fa8f898a98 to your computer and use it in GitHub Desktop.
console.log(this); // window (global scope)
console.log('\n\n ****************************** \n\n');
this.hafeez = 'Hafeez Syed'; // `this.hafeez` will be `window.hafeez` because this -> window
console.log(this.hafeez); // Hafeez Syed
console.log(window.hafeez); // Hafeez Syed
console.log(hafeez); // Hafeez Syed
console.log('\n\n ****************************** \n\n');
function checkThis() {
console.log(this); // window as function `checkThis` is called from the golbal scope
}
checkThis();
console.log('\n\n ****************************** \n\n');
var hafeez = {
checkMe: function() {
console.log(this);
},
checkThis: function() {
function fullName() {
this.fullName = 'Hafeez Syed';
console.log(this); // window, `this` here is pointing to `window` object not `hafeez` object
}
fullName();
console.log(this.fullName); // undefined because, here `this` is pointing to Object 'hafeez'
console.log(window.fullName); // Hafeez Syed,
},
checkThat: function() {
var that = this;
function fullName() {
that.fullName = 'Hafeez Syed';
console.log(that); // Object {}, unlike `checkThis` example, this` here is pointing to `hafeez` object not `window` object because `this` has been assigned to another variable `that`
}
fullName();
console.log(that.fullName); // Hafeez Syed, because here `that` is pointing to Object 'hafeez'
console.log(window.fullName); // Hafeez Syed,
}
}
hafeez.checkMe(); // Object {}, as function `checkMe` is called by the Object `hafeez`
console.log('\n\n ****************************** \n\n');
var checkFunc = hafeez.checkMe;
checkFunc(); // window, because function `checkFunc` is called from the global scope
console.log('\n\n ****************************** \n\n');
hafeez.checkThis();
console.log('\n\n ****************************** \n\n');
hafeez.checkThat();
console.log('\n\n ****************************** \n\n');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment