地图集合中的未定义对象javascript

时间:2014-08-05 07:41:09

标签: javascript collections map undefined

我有我的自定义类,我想将它存储到地图集合中,但是当我想从地图中获取其中一个值(我的对象的一个​​实例)时,我得到错误,该对象未定义。有没有可能投射物体或什么?如果我推简单的字符串而不是我的自定义类的对象一切都好。有人可以告诉我如何解决这个问题?当然,如果这个问题可以解决。

JS:

function CustomClass(first, second, third){
    this.one = first;
    this.two = second;
    this.three = third;
}

CustomClass.prototype.constains(obj1, obj2){}

...
var dictionary = new Object();
dictionary[key] = CustomClass(1, "lel", 2);
for(var el in dictionary) //here IE debugger shows that I have a right key, but the value is undefined.
{
    if(dictionary[el].contains(something))
    {...}
}

如果这取决于我使用IE10。感谢您的帮助以及提示!

编辑:

如果我使用

dictionary[key] = new CustomClass(1, "lel", 2);

而不是:

dictionary[key] = CustomClass(1, "lel", 2);

它有效,但有人可以告诉我为什么,这样的事情:

dictionary[key] = "lel"; 

没有新的运营商?据我所知,js中的所有内容都是一个对象,所以插入字符串和自定义类的区别是什么? (我是js的新人,很抱歉我的知识不足)

1 个答案:

答案 0 :(得分:1)

正如您已经了解的那样,JS对象是使用函数构造的,但new关键字是关键的。

执行var foo = new Bar()时,解释器不仅会创建一个新对象并将其设置为该构造函数中的this,那么该对象也是构造函数的隐式返回值。

如果省略new,则在Bar this上下文将是默认的(ES5严格模式中的undefined或全局对象 - 通常为{{1}否则),函数的不存在的返回值(即window)将被分配给undefined

可以将普通函数转换为不需要foo关键字的“自动构造函数”:

new

即。该函数可以判断它未使用function Bar(x, y, z) { if (!(this instanceof Bar)) { return new Bar(x, y, z); } ... } 调用,因此请立即使用new调用自己。