关于IIFE的一些笔记

IIFE

IIFE是Immediate invoke function expression的缩写,中文名为立即执行函数,常用来封装组件使用,它的写法是

(function(){
  console.log(123)
})()
// 或
+function(){
  console.log(123)
}()

那为什么我们不可以这样写

function a(){
  console.log(123)
}() // Uncaught SyntaxError: Unexpected token )

要解答这个问题,我们需要先来看看创造函数的方式。

方式1: 函数声明式

function a(){
  console.log(123)
}

方式2: 函数表达式

let a = function(){
  console.log(123)
}

而当我们使用立即执行函数的时候,里面的内容必须为一个函数表达式才可以。
当我们在控制台执行+1,-1,~1!1的时候,其实这些都是表达式,因此在执行~function(){}()时,~function(){}这一部分相当于是一个表达式,所以可以执行。(function(){})也是同理,会把里面的内容变为一个表达式。除此以外,下面这种写法也可以

let a = function(){
  console.log(321)
}()

不过我有两个疑问
let test = function(){ console.log(123) }()
这么写是可行的,当function变成箭头函数,let test = () => { console.log(123) }()就报错了,这是为什么。
当这么写的时候可以

(()=>{
})()

第二个疑问是let test = function(){ console.log(123) }() 可以执行成功,但是我在console.log(test)之后打印的是undefined,这是为什么

IIFE的传参

(function a(win, doc){
console.log(window)
console.log(a.length) // 形参
console.log(arguments) // 实参
})(window)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值