“with”这个词有一个有趣的怪癖。 javascript 和父/子窗口中的关键字
我注意到 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”会切换到父窗口,但现在它有意义了。
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 implicit onfocus to the parent window, as well. I didn't realize "with" would switch to the parent window, but it makes sense now.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发生这种情况是因为在 Web 浏览器中运行 javascript 时
window
是全局命名空间。当您编写时:您实际上是在调用
window.alert
方法。This happens because
window
is the global namespace when running javascript in a web browser. When you write:You are actually calling the
window.alert
method.