Advertisement
Guest User

window this

a guest
Oct 28th, 2011
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 1.45 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>window this</title>
  6. <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
  7. <script type="text/javascript">
  8. (function($)
  9. {
  10.     function init()
  11.     {
  12.         window.name = 'parent';
  13.        
  14.         window.meh = function()
  15.         {
  16.             alert('meh:' + this.name);
  17.         }
  18.        
  19.         $("#create").click(function()
  20.         {
  21.             // Open an empty popup we're going to fill in js (so that demo requires only one file)
  22.             var W = window.open('', 'myWindow');
  23.             W.name = 'child';
  24.            
  25.             // Using writeln, which is extacly like referencing a js file for my example
  26.             W.document.writeln('<html><head>'+
  27.             '<title>newWindow</title>'+
  28.             '</head><body>'+
  29.             '<script type="text/javascript">'+
  30.             //'alert(this.name);'+ // this is resolved to W (popup window), so alert outputs 'child'
  31.             //'window.opener.meh();'+ // guess what, 'child' or 'parent'? 'parent' of course !
  32.             'var MEH = window.opener.meh; MEH();'+ // and now ? yeah 'child'
  33.             '</scr'+'ipt>'+
  34.             '</body></html>');
  35.         });
  36.        
  37.         var MEH = window.meh; MEH(); // 'parent'
  38.        
  39.         /*
  40.             Take a careful look at the 2 MEH() calls.
  41.             `this` resolution depends on where the js source that triggers the call stack is coming from.
  42.             Not we're the function currently executed is written (meh function declaration).
  43.         */
  44.     }
  45.    
  46.     $(init);
  47. })(jQuery);
  48. </script>
  49. </head>
  50. <body>
  51.   <input type="button" id="create" value="Click Me" />
  52. </body>
  53. </html>
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement