有趣的怪癖与javascript和父/子窗口中的“with”关键字

时间:2011-06-16 15:24:51

标签: javascript window parent with-statement window.opener

我注意到javascript中的“with”关键字以及父窗口和子窗口关系,特别是window.opener。我没有从父窗口测试这个,只是孩子,但在下面的例子中值得注意 -

父窗口(Parent.html):

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

子窗口(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");
}

在这种情况下,“with”关键字切换到父窗口,第二个警报也会向父窗口触发隐式onfocus。我没有意识到“with”会切换到父窗口,但现在有意义了。

1 个答案:

答案 0 :(得分:1)

这是因为window是在Web浏览器中运行javascript时的全局命名空间。当你写:

alert('Hello, World!');

您实际上正在调用window.alert方法。