一元操作符+function
个人总结
!/+/-/~与function
- 在一些库或者框架的源码中经常看到
!function(){}
,~function(){}
这样的格式 - 原理:
- 我们在调用匿名函数时,会用括号将函数包起来然后调用
- 其实括号真正做的并不是把函数看做一个整体,而是消除歧义,让浏览器能够正确识别
- 在函数前面加一元操作符作用也是如此
- 作用:让一个函数声明句式变成表达式
// function () { // console.log('hello emt!') // }() //报错 浏览器不能正确识别 (function () { console.log('hello emt!') //hello emt! })() !function () { console.log('hello emt!') //hello emt! }() ~function () { console.log('hello emt!') //hello emt! }()
- 推荐阅读:
优雅实现,优雅代码。