Javascript 是否在函数外部更新函数内的变量?

Javascript 是否在函数外部更新函数内的变量?,javascript,cordova,Javascript,Cordova,我正在使用PhoneGap LocalNotification插件,它允许我在特定时间设置本地通知 LocalNotification插件的基本结构如下所示: var notification = { init: function () { }, clear_all: function () { notification.clear(); plugins.localNotification.add({ badge:

我正在使用PhoneGap LocalNotification插件,它允许我在特定时间设置本地通知

LocalNotification插件的基本结构如下所示:

var notification = {
    init: function () {

    },
    clear_all: function () {
        notification.clear();
        plugins.localNotification.add({
            badge: 0,
        });

    },
    alert_ten: function () {
        var d = new Date();
        d = d.getTime() + 10 * 1000; //60 seconds from now
        d = new Date(d);
        plugins.localNotification.add({
            date: d,
            repeat: 'daily',
            message: varone + ' - ' + vartwo + '!',
            hasAction: true,
            badge: 1,
            id: '1',
            sound: 'horn.caf',
            background: 'app.background',
            foreground: 'app.running'
        });
    },
}
如果查看通知的消息部分,它由以下内容组成
varone+'-'+vartwo+'!'。在页面加载时,
varone
vartwo
localStorage
项填充。然后我调用
notification.alert\u ten()
onLoad

这一切都很好,但有一个例外:

localStorage
项是在用户与某个div交互时设置的,即单击该div。然后,当应用程序加载时,它会检查以查看这些值,并在10秒后警告消息,说
this
that
,它们从LS获取值

如果用户改变了主意,并与不同的div交互,从而更改了LS项,则LocalNotification仍将与原始的LS项集一起运行

这是意料之中的,因为JS将在函数中缓存变量。我认为可行的解决方案是在
var notification={
上方全局定义变量,然后当用户与div交互时,更新变量以表示新变量

全局变量:

var varone = localStorage.getItem("favorite");
var vartwo = localStorage.getItem("favorite-status").substr(2).toLowerCase();
...
...
var varone = text;
var vartwo = favstatus;
...
更新的变量:

var varone = localStorage.getItem("favorite");
var vartwo = localStorage.getItem("favorite-status").substr(2).toLowerCase();
...
...
var varone = text;
var vartwo = favstatus;
...

函数,
notification.alert\u ten()
仍然使用全局变量中定义的原始值而不是更新的值运行。

您可以编写getter/setter函数。这只是一个概念证明,您可以添加任何您喜欢的方法。只需确保在要在函数内部共享的任何属性之前添加
This。
e对象,或您希望从对象外部访问的对象

var notification = {
  setX : function (newX) {
    this.x = newX;
  },
  getX : function () {
    return this.x;
  },
  outputX : function () {
    document.write('x is ' + this.x + '<br>');
  }
}

甚至

notification.x = 42;
console.log(notification.x);

因此,您的代码可能类似(剔除所有有趣的部分)


另外,我会远离下划线
命名约定。命名函数
clearAll()
alertTen()
时会使用更多javascript语法。是的,我通常在编写代码后更改名称。我不知道为什么,但我知道。
var notification = {
    getMessage: function() {
        return this.message;
    },
    setMessage: function() {
        this.message = localStorage.getItem("favorite") + ' - ' + 
                       localStorage.getItem("favorite-status").substr(2).toLowerCase() + '!';
    },
    alert_ten: function () {
        plugins.localNotification.add({
            message: this.getMessage()
        });
    }
}

// After some event I guess
notification.setMessage();
// After some other event?
notification.alert_ten();