Skip to content

Instantly share code, notes, and snippets.

@mrpollo
Created June 22, 2011 23:30
Show Gist options
  • Save mrpollo/1041551 to your computer and use it in GitHub Desktop.
Save mrpollo/1041551 to your computer and use it in GitHub Desktop.
Javascript wrong use of this in OOP
// Main Class Foo
function foo(){
// Foo has some properties we need to access later
this.test = "hello scope";
// We call a member function on a timer
setTimeout( this.bar, 1000 );
}
foo.prototype.bar = function(){
// once the timer is called it executes this function
// but as a result of using the timer we have lost our referenced parent
// this now becomes the document
// outputting this will return
// Window 127.0.0.1 ( assuming you run on your local box
alert( this );
// thus trying to access this.test will result in trying to access
// the global variable called test or in other words window.test
// which is different than our foo.test
// ( assuming window.test wasn't already defined somewhere else )
alert( this.test );
}
var x = new foo();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment