最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - sharing a js functions between code in 2 files - Stack Overflow

programmeradmin0浏览0评论

My jquery code is divided file is divided over 2 files.

In one of the file, I define a function

function something(input){
  //does something
}

calling this function only works when the caller line is in the same file. But I need to call it from both files.

If I switch the function to the second file, again I get the same issue. The code in the same file can read it, but not the code in the other file.

My jquery code is divided file is divided over 2 files.

In one of the file, I define a function

function something(input){
  //does something
}

calling this function only works when the caller line is in the same file. But I need to call it from both files.

If I switch the function to the second file, again I get the same issue. The code in the same file can read it, but not the code in the other file.

Share Improve this question asked Mar 11, 2011 at 10:21 samisami 1551 gold badge3 silver badges6 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 10

Place your functions outside of $(document).ready(function() { }); to give them global scope. Anything placed within it cannot be accessed from the outside.

You can then look into using a namespace to encapsulate your functions. This helps to avoid clutter of the global namespace.

You need to create a namespace object, which is shared between your files.

fileA.js

window.mynamespace = window.mynamespace || {};

mynamespace.something = function(input) {
    // do something
};

fileB.js

window.mynamespace = window.mynamespace || {};

mynamespace.something();
发布评论

评论列表(0)

  1. 暂无评论