5

我在这里有点困惑......如果我有一个.js文件具有这样的功能:

function myMain() {
    var count=0;
    count++;               
    myHelper(count);
    alert(count);
}

function myHelper(count) {
    alert(count);
    count++;
}

我还能myHelper()在另一个 .js 文件上调用另一个方法吗?或者有没有其他方法可以将计数变量从一个函数传递到另一个函数,然后它将被调用到其他 .js 文件。你对这个有什么想法吗?谢谢!

4

3 回答 3

16

Update: Nowadays you should prefer to use ES6 import/export in a <script> tag with type="module" or via a module bundler like webpack.


When both script files are included in the same page, they run in the same global JavaScript context, so the two names will overwrite each other. So no, you can not have two functions in different .js files with the same name and access both of them as you've written it.

The simplest solution would be to just rename one of the functions.

A better solution would be for you to write your JavaScript modularly with namespaces, so that each script file adds the minimum possible (preferably 1) objects to the global scope to avoid naming conflicts between separate scripts.

There are a number of ways to do this in JavaScript. The simplest way is to just define a single object in each file:

// In your first script file
var ModuleName = {
    myMain: function () {
        var count=0;
        count++;               
        myHelper(count);
        alert(count);
    },

    myHelper: function (count) {
        alert(count);
        count++;
    }
}

In a later script file, call the function ModuleName.myMain();

A more popular method is to use a self-evaluating function, similar to the following:

(function (window, undefined) {

    // Your code, defining various functions, etc.
    function myMain() { ... }
    function myHelper(count) { ... }

    // More code...

    // List functions you want other scripts to access
    window.ModuleName = {
        myHelper: myHelper,
        myMain: myMain  
    };
})(window)
于 2013-02-08T04:54:32.213 回答
-2

如果您知道要覆盖一个方法,您可以先将旧方法存储在一个变量中,然后通过该变量调用该函数的另一个实现。

于 2013-07-24T08:31:26.617 回答
-4

是的,只要将两个 js 文件都包含在一个 html 或 jsp 页面中,就可以从任何其他 js 文件调用 myHelper()

你可能想看看这个: 我们可以在另一个 JS 文件中调用用一个 JavaScript 编写的函数吗?

于 2013-02-08T04:20:24.620 回答