原生JS基础知识
立即执行函数
- 和普通函数的唯一区别 : 此类函数没有声明 , 且会立即执行 , 执行完后立即释放 ( 剪线 ) , 适合做初始化工作
官方的两种写法
(function () {}()); // 推荐
(function () {})();
Tips : 只有表达式才能被执行符号
()
执行
function demo() {
console.log(123); // 函数声明不能被执行
}();
var demo = function () {
console.log(123); // 123
}()
Tips : 能被执行符号执行的 表达式的名字 会被自动忽略 , 以下写法实际上就是立即执行函数
var test = function () {
console.log(123); // 123
}();
console.log(test); // undefined
+ function test() {
console.log(123); // 123
}();
console.log(test); // test is not defined
- function test() {
console.log(123); // 123
}();
console.log(test); // test is not defined
! function test() {
console.log(123); // 123
}();
console.log(test); // test is not defined