【问题标题】:Can't access item in a javascript associative array无法访问 javascript 关联数组中的项目
【发布时间】:2012-07-13 16:32:21
【问题描述】:

我在一个名为 thing.js 的文件中有一个 javascript“模块”(我们在 python 中称它们为):

function Thing(){
this.a = "foo";
this.b = "bar";
this.c = "";

this.d = function(){
    this.c = this.a + this.b;
};
};

var things = {
'one':Thing(),
'two':Thing(),
'three':Thing()
};
alert(things["one"]); // output: undefined!!??

/* Pick out two random items from things. */
var random_thing = function(){
    //var grabbed = 0;
    //while(grabbed < 1){
var pick = getRandomInt(0,2);
alert(things["one"]); // output: undefined!!
    //if ()
    //return pick;
};

代码有点不完整,我想从东西中随机挑出两个项目并返回。不过,这不是当前的问题。

我有一个名为 main.js 的单独“主”javascript 文件,它调用这些对象和函数:

$div1.append(random_thing());

在我的 html 文件中,我包含了两个 javascript 文件:

<script type="text/javascript" src="thing.js"></script>
<script type="text/javascript" src="main.js"></script>

但我不断得到的输出是“未定义”的警报(事物['one'])!我不明白第一个警报是如何返回未定义的,它就在事物关联数组的定义之下。

【问题讨论】:

    标签: javascript module associative-array


    【解决方案1】:

    调用 Thing() 除了破坏 window 属性之外,对您没有任何帮助。你正在寻找new Thing()

    var things = {
        'one': new Thing(),
        'two': new Thing(),
        'three': new Thing()
    };
    

    如果您在不使用 new 关键字的情况下调用“类”函数,则 this 将引用 window 全局对象,这几乎可以确保事情会出错 - 有时非常糟糕。当您确实使用new 关键字时,this 将引用一个全新的对象,该对象将自动返回。

    这是 JavaScript“类”的常见问题,并且(在我看来)最好通过使用创建函数来避免:

    function Thing() {
        this.a = "foo";
        this.b = "bar";
        this.c = "";
    
        this.d = function(){
            this.c = this.a + this.b;
        };
    };
    Thing.create = function() {
        return new Thing();
    };
    
    var things = {
        'one': Thing.create(),
        'two': Thing.create(),
        'three': Thing.create()
    };
    

    这里的目标是永远不要依赖于创建函数之外的 new 关键字。

    【讨论】:

      猜你喜欢
      • 2011-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多