立即函式特點:
接著我們來看立即函式的語法
(function() {
    console.log('立即函式');
})();

此時能看見只要使用立即函式,函式內容會馬上執行,
因此才會回傳 '立即函式'
以下會列出立即函式的功能
在立即函式中的變數,其作用域只在函式內
(function() {
    const ming = '小明';
    console.log(ming);  // 小明
})();
console.log(ming);  // ming is not defind

能夠看見立即函式中的 ming 有被回傳,
但函式外的卻是 ming is not defind
(function(where) {
    console.log(where);
})('weiwei');

我們將 'weiwei' 代入立即函式中,能看見回傳 weiwei
而立即函式為表達式,因此可以使用 return 來將值賦予到變數中,
const whereWei = (function(where) {
    return where;
})('weiwei');
console.log(whereWei);

我們也可以使用兩個立即函式來傳遞值
const a = {};
(function(b) {
    b.person = 'weiwei';
})(a);
(function(c) {
    console.log(c.person);
})(a);

它會先由第一個立即函式中賦予 a 物件 person 屬性,
再由第二個立即函式將值回傳,
而這也能使用在 window 上
(function(global) {
    global.person = 'weiwei';
})(window);
(function() {
    console.log(person);
})();

這種方式主要會用在大型的框架上,
以 Vue2 為例:
我們能在開頭看到是使用立即函式將 Vue 的內容寫入全域當中

而結尾是將 Vue 的內容定義完後進行回傳

以上就是今天立即函式的內容了,感謝觀看!!