原生JS基础知识(九)

原生JS基础知识

我的github

立即执行函数

  • 和普通函数的唯一区别 : 此类函数没有声明 , 且会立即执行 , 执行完后立即释放 ( 剪线 ) , 适合做初始化工作

官方的两种写法

(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
发布了49 篇原创文章 · 获赞 29 · 访问量 1916

猜你喜欢

转载自blog.csdn.net/Brannua/article/details/104342439
今日推荐