简体   繁体   中英

IIFE reference error variable not defined inside the function?

I'm practicing my js functions and came through an error that is not so obvious for a beginner. The problem is the function won't define my second variable. It works when I declare my variables outside, but I'm interested on the inside. Heres the code.

(function (firstname, lastname){
    var firstN = 'Hubba';
    var lastN = 'Bubba';
    console.log(firstname + ' ' + lastname)
}(firstN, lastN));

That's because inside the function the variables firstN and lastN are local variables to the functions scope. This means they only exist inside of your function when you execute it.

So when you try to call your function by doing (function(..){...}(firstN, lastN)) those variables you pass are outside the scope of your function, as such they aren't defined.

For example if I did:

 var firstN = 'Hubba_1'; var lastN = 'Bubba_1'; (function (firstname, lastname){ var firstN = 'Hubba_2'; // Not needed var lastN = 'Bubba_2'; // Not needed console.log(firstname + ' ' + lastname) }(firstN, lastN)); 

You will notice that it prints Hubba_1 and Bubba_1 . The outside firstN and lastN are entirely different variables compared to the variables firstN and lastN inside your function.

You're asking for the firstN and lastN values outside of the scope of your IIFE, which are undefined in the outer scope. Look into how block scope works.

 // SO snippets don't allow undefined vars so we can mimic it using `window` like would be in the browser var window = {}; console.log(window.firstN); //undefined console.log(window.lastN); //undefined var firstN = "Foo"; var lastN = "Bar"; (function(firstname, lastname){ var firstN = "Happy"; var lastN = "Go Lucky"; console.log(firstname + " " + lastname); // 'Foo Bar' console.log(firstN + " " + lastN); // 'Happy Go Lucky' })(firstN, lastN) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM