Last active
July 24, 2017 13:19
-
-
Save tekaratzas/a50ce0abf6b460d92767161d4ff2b1e5 to your computer and use it in GitHub Desktop.
Where "this" gets weird in JS
This file contains hidden or 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
function test() { | |
this.arr = [1,2,4]; | |
this.message = "I am here"; | |
this.fun = function() { | |
this.arr.forEach(function(item) { | |
console.log(this.message); // will print undefined 3 times since this refers to the global object | |
}); | |
} | |
} | |
var t = new test(); | |
t.fun(); | |
// In the above code, "this" WILL NOT refer to the test object but instead the global object | |
//to get around this, you can use a variable to store "this" when it does refer to test | |
// Since "this" still refers to the object, it will also get updated when using the substitute variable. | |
function test2() { | |
var self = this; | |
self.arr = [1,2,4]; | |
self.message = "I am here"; | |
self.fun = function() { | |
this.arr.forEach(function(item) { | |
console.log(self.message); // prints "I am Here" 3 times | |
}); | |
} | |
} | |
var t2 = new test2(); | |
t2.fun(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment