You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

从script标签调用外部JS函数遇引用错误,Firebase调用可执行?是否为作用域问题

解答:这确实是典型的作用域问题!

Absolutely—this is definitely a scoping issue, and it’s a super common gotcha when working with self-executing functions (IIFEs) in JavaScript. Let me break down exactly what’s happening:

1. Why direct calls to readInData() fail

If your external.js wraps readInData() inside an IIFE (a self-executing anonymous function), that function is only accessible within the scope of that IIFE. JavaScript scopes variables/functions to the block (or function) they’re defined in—so when you try to call readInData() from outside that IIFE (like your global code), the runtime can’t find it, hence the uncaught reference error.

Here’s what your external.js likely looks like under the hood:

// external.js
(function() {
  // This function is trapped inside the IIFE's local scope
  function readInData() {
    // Your data-reading logic
  }
})();

// Global scope attempt: fails because readInData isn't exposed
readInData(); // Uncaught ReferenceError: readInData is not defined

2. Why it works inside Firebase calls

Firebase’s asynchronous methods (like get(), onSnapshot(), or then() callbacks) are probably defined inside the same IIFE as readInData(). Since those callbacks share the same scope chain as readInData, they can access the function directly without any issues.

Example of this working scenario:

// external.js
(function() {
  function readInData() {
    // Your data-reading logic
  }

  // Firebase call lives inside the IIFE, so it can access readInData
  firebase.firestore().collection("your-collection")
    .get()
    .then(() => {
      readInData(); // Works perfectly—same scope!
    });
})();

Fixes to make readInData() globally accessible

If you need to call readInData() from outside the IIFE, you have a couple of solid options:

Option 1: Expose the function to the global scope (browser environment)

Attach the function to the window object, which makes it accessible anywhere in your code:

(function() {
  function readInData() {
    // Your data-reading logic
  }

  // Expose to global scope
  window.readInData = readInData;

  // Firebase call still works as before
  firebase.firestore().collection("your-collection")
    .get()
    .then(() => {
      readInData();
    });
})();

// Now this global call works!
readInData();

Option 2: Use ES Modules (modern projects)

If your project uses ES modules (with import/export), restructure external.js to export the function:

// external.js (as an ES module)
export function readInData() {
  // Your data-reading logic
}

// Firebase call still works
firebase.firestore().collection("your-collection")
  .get()
  .then(() => {
    readInData();
  });

Then import it wherever you need to call it:

// In your other script file
import { readInData } from "./external.js";

readInData(); // Works!

内容的提问来源于stack exchange,提问作者Mike

火山引擎 最新活动