问题描述
我正在学习NativeScript.作为其中的一部分,我正在尝试一个基本项目.在该项目中,我试图使用一个用于字符串处理的JavaScript文件.该文件不需要访问诸如DOM之类的浏览器元素.但是,包含文件时我无法运行我的应用程序.目前,我的./app/home/index.js文件中包含以下内容:
I am learning NativeScript. As part of that, I'm trying out a basic project. In that project, I'm trying to use a JavaScript file that I use for string manipulation. This file does NOT require access to browser elements like the DOM. Yet, I can't run my app when I include the file. At this time, I have the following in my ./app/home/index.js file:
var MyFile = require('../app/code/myFile.js');
...
var prefix = myFile.GetPrefix(someStringValue);
有关更多背景信息:
- 我已将文件包含在./app/code/myFile.js中.
- 我已经引用了如上所示的文件
这是myFile.js的样子:
Here is what myFile.js looks like:
function MyClass() {}
module.exports = MyClass;
MyClass.test = function(msg) {
console.log(msg);
};
如何在NativeScript应用程序中使用一些现有的JavaScript?
How can I use some existing JavaScript in a NativeScript app?
谢谢!
推荐答案
您需要在 index.js 中使用 MyClass 的实例.您可以在以下实例中实例化 MyClass :
You need an instance of MyClass in index.js. You can instantiate MyClass either in:
-
index.js :
var myFileModule = require('../app/code/myFile.js');
var myFileModule = require('../app/code/myFile.js');
var myFile = new myFileModule.MyClass();
var myFile = new myFileModule.MyClass();
或...
-
myFile.js :
module.exports = new MyClass();
module.exports = new MyClass();
::请注意,如果您执行上面的#2,则在您的代码中...
:: Note that if you do #2 above, in your code...
var MyFile = require('../app/code/myFile.js');
... MyFile变量已经是MyClass的实例.
::关于编码风格的一个小小的,不相关的建议:最好将变量命名为 myFile 而不是 MyFile (请注意myFile中的第一个小写字母) ...
:: A small, unrelated suggestion on coding style: It's better to name your variable(s) myFile instead of MyFile (note the first lowercase letter in myFile)...
这篇关于在NativeScript中使用JavaScript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!