Javascript,变量没有被分配...为什么?

时间:2011-08-25 03:25:11

标签: javascript variable-assignment

这是我最简单的代码:

var this_version =null;

this.timervar = setTimeout(function () {
    try {
        // Firefox 4 and later; Mozilla 2 and later
        Components.utils.import("resource://gre/modules/AddonManager.jsm");
        AddonManager.getAddonByID("parasites@maafire.com", function(addon) {
            this_version = addon.version;
            alert("r "+this_version);
        });
    } catch (ex) {
        // Firefox 3.6 and before; Mozilla 1.9.2 and before
        var em = Components.classes["@mozilla.org/extensions/manager;1"]
            .getService(Components.interfaces.nsIExtensionManager);
        var addon = em.getItemForID("parasites@maafire.com");
        this_version = addon.version;
        alert("rr " + this_version);
    }
    alert("rrr " + this_version);
}, 2000);

它真是太奇怪了,因为这会引发两次alert("r "+this_version);,但这个alert("rrr "+this_version);总是让我无效;(

还在学习JS,所以这很令人费解......请帮忙!

谢谢!

3 个答案:

答案 0 :(得分:0)

设置this_version变量的代码位于回调中,因此对变量的更改不会反映在第三个alert执行的范围内。

答案 1 :(得分:0)

这是在JavaScript世界中实现它的正确方法:

function done() {
    alert("rrr "+this_version);
}

var this_version =null;
try {
    // Firefox 4 and later; Mozilla 2 and later
    Components.utils.import("resource://gre/modules/AddonManager.jsm");
    AddonManager.getAddonByID("parasites@maafire.com", function(addon) {
        this_version = addon.version;
        alert("r "+this_version);
        done();
    });
} catch (ex) {
    // Firefox 3.6 and before; Mozilla 1.9.2 and before
    var em = Components.classes["@mozilla.org/extensions/manager;1"]
        .getService(Components.interfaces.nsIExtensionManager);
    var addon = em.getItemForID("parasites@maafire.com");
    this_version = addon.version;
    alert("rr " + this_version);
    done();
}

甚至更好:

function done(version) {
    alert("rrr "+version);
}

然后这样称呼:

done(this_version);

答案 2 :(得分:-1)

好的,只需移动计时器以外的所有内容即可解决它:

var this_version =null;
try {
    // Firefox 4 and later; Mozilla 2 and later
    Components.utils.import("resource://gre/modules/AddonManager.jsm");
    AddonManager.getAddonByID("parasites@maafire.com", function(addon) {
        this_version = addon.version;
        alert("r "+this_version);
    });
} catch (ex) {
    // Firefox 3.6 and before; Mozilla 1.9.2 and before
    var em = Components.classes["@mozilla.org/extensions/manager;1"]
        .getService(Components.interfaces.nsIExtensionManager);
    var addon = em.getItemForID("parasites@maafire.com");
    this_version = addon.version;
    alert("rr " + this_version);
}

this.timervar = setTimeout(function ()
                            { 



                                    alert("rrr "+this_version);


                            }, 2000);