在JavaScript中添加全局变量/函数(特别是NativeScript) [英] Adding a global variable / function in JavaScript (specifically NativeScript)

查看:103
本文介绍了在JavaScript中添加全局变量/函数(特别是NativeScript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何使用NativeScript编写应用程序。我相信最好的学习方法就是做。出于这个原因,我正在构建一个基本的应用程序。

I'm learning how to write apps with NativeScript. I believe the best way to learn is by doing. For that reason, I'm building a basic app.

在这个应用程序中,我正在尝试创建一个函数和一个变量,我可以访问所有视图模型和应用程序中的其他代码。为了做到这一点,我想我会在应用程序对象上添加一个函数和变量。

In this app, I'm trying to create a function and a variable that I can access across ALL of the view models and other code in the app. In an attempt to do this, I thought I would add a function and variable on the application object.

在NativeScript中,使用以下代码初始化应用程序:

In NativeScript, the app is initialized using the following code:

app.js

var application = require("application");
application.mainModule = "main-page";
application.start();

我想我可以捎带这个并添加一个全局可见的函数和变量,如下所示:

I figured I could piggy back on this and add a globally visible function and variable like so:

application.prototype.myFunction = function() {
  console.log('I made it!');
};
application.myVariable = 'some value';

然后,在我的视图模型或其他代码中,我可以执行以下操作:

Then, in my view models, or other code, I could just do something like the following:

views / home.js

application.myFunction();
console.log(application.myVariable);

但是,当我运行此代码时,我收到一条错误消息,指出该应用程序未定义。我不完全理解这一点。我认为,因为应用程序在app.js中定义/实例化,它将全局可见。但是,它似乎不是。与此同时,我不知道该怎么做。

However, when I run this code, I get an error that says that application is undefined. I do not fully understand this. I thought that because application is defined/instantiated in app.js that it would be globally visible. However, it does not seem to be. At the same time, I'm not sure what to do.

推荐答案

使用全局命名空间。在您的 app.js 中,代码:

Use the global namespace. In your app.js, code:

var application = require("application");
application.mainModule = "main-page";

global.myVariable = 'some value';

application.start();

然后,您可以在应用中的任何位置使用 global.myVariable

You can then use global.myVariable anywhere in your app.

这篇关于在JavaScript中添加全局变量/函数(特别是NativeScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆