【问题标题】:Interesting quirk with the "with" keyword in javascript and parent/child windowsjavascript 和父/子窗口中的“with”关键字的有趣怪癖
【发布时间】:2011-06-16 15:24:50
【问题描述】:

我注意到 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”会切换到父窗口,但现在它很有意义。

【问题讨论】:

  • 尽量避免使用with关键字...永远。它正在退出 JavaScript 语言。因此,您编写的任何程序都会在现代浏览器中中断。
  • 好的,谢谢。这只是一个学术练习。我认为它是为那些避免 oop 并喜欢程序的人创建的。

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


【解决方案1】:

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

alert('Hello, World!');

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多