Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

void 与 立即执行函数表达式 #132

Open
lovelmh13 opened this issue Jul 26, 2021 · 0 comments
Open

void 与 立即执行函数表达式 #132

lovelmh13 opened this issue Jul 26, 2021 · 0 comments

Comments

@lovelmh13
Copy link
Owner

一般在使用立即执行函数表达式的时候,我们这么写:

(function foo() {
    console.log(1)
})()

如果使用 void ,就可以不用写 () 来包裹函数

void function foo() {
    console.log(1)
}()

void 运算符对给定的表达式进行求值,然后返回 undefined

如果既不用 () 扩起来,也不用 void ,则会报错

function foo() {
    console.log(1)
}()// Uncaught SyntaxError: Unexpected token ')'

void 的作用

一般来说, void 都是用 void(0) 来获取 undefined ,因为 undefined 在浏览器中,在局部作用域中可以被修改,全局作用域中,不能被修改;而在 node 环境下,均可被修改。但是用 void(0) 就可以保证取到都是 undefined

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant