如何调用在其他 JavaScript 文件中定义的静态 JS 函数

How to call a static JS function defined in other javascript file

本文关键字:定义 文件 静态 函数 JS JavaScript 其他 何调用 调用      更新时间:2023-09-26

我正在使用Meteor JS。我在文件 A 中定义了一个 JavaScript 函数,我想通过从文件 B 调用来重用它。

文件 A:

function Storeclass(){}
Storeclass.validate=function(){...}

从 A JavaScript 我尝试调用它工作StoreClass.validateBasic()但相同的调用从 B 不起作用。我也尝试在 B 中做var storeClassObj=new StoreClass();storeClassObj.validate().我收到错误ReferenceError: StoreClass is not defined.

阅读此文档,了解 Meteor 中的命名空间。

相关部分是这样的:

// File Scope. This variable will be visible only inside this
// one file. Other files in this app or package won't see it.
var alicePerson = {name: "alice"};
// Package Scope. This variable is visible to every file inside
// of this package or app. The difference is that 'var' is
// omitted.
bobPerson = {name: "bob"};

但是,稍后在同一文档中,它是这样说的:

声明函数时,请记住函数 x () {} 只是 JavaScript 中 var x = 函数 x () {} 的简写。

这表明您编写的函数是文件 A 的私有函数,即使加载顺序正确,也无法从文件 B 访问!

因为文件 B 中的函数可能会在文件 A 准备就绪之前调用,因此您必须确保成功加载所有必需的 js 文件。

如果您使用的是jQuery,那么在文件B中调用文档就绪函数中的函数:

$( document ).ready(function() {
    //File A code
});

或者用普通的JavaScript:

(function() {
   // your page initialization code here
   // file A code
})();