Tuesday, July 9, 2013

Using self in javascript closures

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.



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();

1 comment:

  1. We provide the best online tech support (live technical support). We're here to answer your questions and help you use all your devices. We provide all kind of online tech services like Desktop or Laptop support, Printer support, online live technical support, Antivirus programs, popup blocker etc.

    ReplyDelete