开发者

Interesting quirk with the "with" keyword in javascript and parent/child windows

I noticed something peculiar about the "with" keyword in javascript and the parent and child window relationship, specifically window.opener. I haven't tested this from the parent window, just the child, but it is worth noting in the example below--

Parent window (Parent.html):

// global scope
function ParentFunc() { alert("I am a parent function"); }

Child window (Child.html):

// global scope
var baseWin = window.opener;

// "this" keyword corresponds to Child.html when function below is called
function Child_Onclick_Func()
{
  alert("Hi, from Child");
  with (baseWin)
  {
    ParentFunc();
    alert("Hi, from Parent");
  }
  alert("Hi, back to Child");
}

The "with" keyword, in this case, switches to the parent window and the second alert fires an imp开发者_StackOverflow社区licit onfocus to the parent window, as well. I didn't realize "with" would switch to the parent window, but it makes sense now.


This happens because window is the global namespace when running javascript in a web browser. When you write:

alert('Hello, World!');

You are actually calling the window.alert method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜