问题
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);
For more background:
- I've included the file in ./app/code/myFile.js.
- I've referenced the file as shown above
Here is what myFile.js looks like:
function MyClass() {}
module.exports = MyClass;
MyClass.test = function(msg) {
console.log(msg);
};
How can I use some existing JavaScript in a NativeScript app?
Thank you!
回答1:
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 myFile = new myFileModule.MyClass();
OR...
myFile.js:
module.exports = new MyClass();
:: Note that if you do #2 above, in your code...
var MyFile = require('../app/code/myFile.js');
... the MyFile variable already IS an instance of MyClass.
:: 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)...
来源:https://stackoverflow.com/questions/31482486/using-javascript-files-in-nativescript