This and that in JavaScript - or self as I've seen it, is just a workaround for the fact that in JavaScript, inner function "this" is not behaving like "this" from the outer function, it points to the window object.. Yes, it's a bug, and it will be fixed in ECMA5.
Closure mechanism - an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.
Something like this:
To preserve outer function "this", putting "this" into local variable ("that" or "self") will allow transfer of variable from outer function to be used, by using closures.
Closure mechanism - an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.
Something like this:
<!DOCTYPE html><html lang="en"><head></head> <body><script>var myObject = { myProperty:'Some text here', myMethod:function() { var that = this; //reference to myObject in myMethod scope var innerFunction function() { // inner one console.log(that.myProperty); //logs 'Some text here' console.log(this); // logs window object to show what will happen if we don't store this into that }(); }}myObject.myMethod(); // invoke myMethod</script></body></html>
No comments:
Post a Comment