Welcome...



...All those moments will be lost in time, like tears in rain....

- soliloquy from Blade Runner


Bits and bytes do get lost, awash in the rain of data flow that is Internet. They slip away from us, never to found again... some of them will be captured here, many more will not... like tears in rain...



Wednesday, March 6, 2013

This and that in JavaScript

 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.

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