原生JS基础知识(九)

十年热恋 提交于 2020-02-16 16:50:28

原生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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!