如何清空JavaScript函数实际上做了什么? [英] How can empty JavaScript function actually do something?
问题描述
在尝试了解网络服务器的运作方式时,我偶然发现:
While trying to understand how a web server worked, I came accross this:
//myfile.js
function donothing(){};
//myfile.html
javascript:donothing(open('http://www.acme.com/whatever.jpg','','left=100, right=0, top=100, scrollbars=no, status=no, titlebar=no, resizable=no, toolbar=no, menubar=no, width=255, height=255'))
我不是JavaScript专家,所以我不知道如何使用空函数。有人知道吗?
I'm no JavaScript expert, so I don't get how an empty function can be made to work. Does someone know?
谢谢。
推荐答案
这是一个自制 void
替换以避免表达式返回值。
This is a homemade void
substitute to avoid having the expression return a value.
window.open
将返回对打开窗口的引用,这可能会产生意外结果。
window.open
will return a reference to the opened window, and this can have unexpected results.
例如,尝试粘贴 javascript: a = 1
进入地址字段 - 这将导致一个空白的屏幕,其中的数字为1,因为浏览器默认会尝试使用任何表达式的结果作为新文档运行。
For instance, try pasting javascript:a=1
into the address field - this will result in a blank screen with the number 1 in it as the browser will by default try to use the result of any expression run as the new document.
为了避免这种情况,你使用 javascript:void(a = 1)
因为void不会返回任何内容,因此结果不用作新文档。
To avoid this you use javascript:void(a=1)
as void will not return anything, and so the result isn't used as the new document.
使用 donothing(foo = bar)
或等效的 Function.prototype(foo = bar)
不需要,因为内置的 void
完全相同。
Using donothing(foo=bar)
or the equivalent Function.prototype(foo=bar)
is not needed as the built-in void
does the exact same.
但是请注意,在c时,使用void只需要 将文本添加到地址字段中,当你在链接中使用伪协议 javscript:
时,它是不必要的(你永远不应该这样做)。
But mind, the use of void is only needed when copying text into the address field, its not necessary when you use the pseudo protocol javscript:
in links (which you should never do anyway).
这篇关于如何清空JavaScript函数实际上做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!