简体   繁体   English

如何获取JavaScript文件的对象(句柄)?

[英]How to get an object(handle) of a javascript file?

I am using requireJS and I have two files (app,js and file1.js). 我正在使用requireJS,我有两个文件(app,js和file1.js)。 I need to instantiate file1.js in app.js using require() and then call a function in file1.js from app.js. 我需要使用require()实例化app.js中的file1.js,然后从app.js调用file1.js中的函数。 How do I do that? 我怎么做?

app.js app.js

define(function(require){
    var file1 = require('file1.js');
    file1.load_function();
}

file1.js file1.js

define([], function(){
    var load_function = function(){
        //Some logic
    }
}

But here, the "load_function()" is being loaded without being invoked. 但是在这里,“ load_function()”被加载而没有被调用。 And there is error in the way I am using "var file1" as a handle. 我使用“ var file1”作为句柄的方式存在错误。

Is there a way I can get a handle on "file1.js" from "app.js"? 有没有办法可以从“ app.js”获取“ file1.js”的句柄?

How can prevent the function from loading(executing) without it being invoked? 如何防止该函数在不被调用的情况下加载(执行)?

There is no error in your app.js file. 您的app.js文件中没有错误。 The line var file1 = require('file1.js'); var file1 = require('file1.js'); loads the module file1.js and binds it to the local variable file1 . 加载模块file1.js并将其绑定到本地变量file1 Then you can call file1.load_function() . 然后,您可以调用file1.load_function()

You need to export your function: 您需要导出函数:

define(function (require, exports, module) {
    var load_function = function(){
        //Some logic
    }
    exports.load_function = load_function;
});

By the way you should never put the .js extension in your module names so refer to the module in the file named file1.js as file1 . 顺便说一句,您永远不要在模块名称中添加.js扩展名,因此,将名为file1.js的文件中的模块称为file1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM