What does “[removed]void(0)” mean?

前端 未结 14 1367
说谎
说谎 2020-11-21 15:23
login

I\'ve seen such hrefs many times, but I don\'t know what exactly

14条回答
  •  一生所求
    2020-11-21 16:17

    To understand this concept one should first understand the void operator in JavaScript.

    The syntax for the void operator is: void «expr» which evaluates expr and returns undefined.

    If you implement void as a function, it looks as follows:

    function myVoid(expr) {
        return undefined;
    }
    

    This void operator has one important usage that is - discarding the result of an expression.

    In some situations, it is important to return undefined as opposed to the result of an expression. Then void can be used to discard that result. One such situation involves javascript: URLs, which should be avoided for links, but are useful for bookmarklets. When you visit one of those URLs, many browsers replace the current document with the result of evaluating the URLs “content”, but only if the result isn’t undefined. Hence, if you want to open a new window without changing the currently displayed content, you can do the following:

    javascript:void window.open("http://example.com/")
    

提交回复
热议问题