调用立即执行函数表达式(IIFE)时遭遇类型错误求助
Hey there! Let's break down why your code is throwing that type error and fix it right away.
What's Wrong With Your Original Code?
Your code mixes object definition with an Immediately Invoked Function Expression (IIFE) in a way that confuses JavaScript. Here's your code again for reference:
var content = { x: 5, y: 7 } (objectData => { for(let key of Object.keys(objectData)){ console.log(`${key} : ${objectData[key]}`); } }) (content);
When JavaScript parses this line, it sees { x: 5, y: 7 } followed by (...) — it tries to treat the object literal as a function to call, which is impossible (plain objects aren't callable). That's exactly why you're getting a type error. On top of that, you're trying to reference content before it's fully defined, which would cause another issue even if the first part worked.
Fixed Code Options
Option 1: Separate Object Definition and Function Call
This is the clearest approach — define your object first, then pass it to your function:
// Define your object first var content = { x: 5, y: 7 }; // Call the IIFE with your object as the argument ((objectData) => { for(let key of Object.keys(objectData)){ console.log(`${key} : ${objectData[key]}`); } })(content);
Option 2: Pass the Object Directly to the IIFE
If you don't need to reuse the content variable later, you can pass the object directly to the IIFE without assigning it first:
((objectData) => { for(let key of Object.keys(objectData)){ console.log(`${key} : ${objectData[key]}`); } })({ x: 5, y: 7 }); // Directly pass the object literal
Option 3: Assign the Object and Run the Function in One Line (If Needed)
If you want to both assign the object to content and run the function in a single line, you can have the IIFE return the object after processing it:
var content = ((objectData) => { for(let key of Object.keys(objectData)){ console.log(`${key} : ${objectData[key]}`); } return objectData; // Return the object to assign to content })({ x: 5, y: 7 });
Why These Fixes Work
- In Option 1, we separate object creation from the function call, so JavaScript never tries to treat the object as a function.
- In Options 2 and 3, wrapping the IIFE in parentheses
((...) => {...})ensures JavaScript recognizes it as a function expression, not a code block. Passing the object directly removes any confusion about what's being executed.
内容的提问来源于stack exchange,提问作者Kenny Omega

