The setTimeout function in javascript is very interesting in the sense that when it is called, the window object calls it.
Therefore, the original reference to the "this" object is changed; however, to overcome this we can make a copy of the "this" reference related to the closure inside the test function.
Here we call that variable self. This way, when the setTimeout function is called the email is not undefined.
Therefore, the original reference to the "this" object is changed; however, to overcome this we can make a copy of the "this" reference related to the closure inside the test function.
Here we call that variable self. This way, when the setTimeout function is called the email is not undefined.
var b = 'test';
//creates an object literal with a function called ;
var x = {
email: 'test@test.com',
alertEmail: function() {
var self = this;
setTimeout(function(){
alert(self.email);
}, 1000);
}
};
//alerts test@test.com
x.alertEmail();