[英]Can't access item in a javascript associative array
我在名为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>
但是我不断得到的输出对于alert(things ['one'])是“未定义”的! 我不明白第一个警报如何返回未定义状态,它正好在事物关联数组的定义下方。
调用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
关键字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.