1

In Loop through a 'Hashmap' in JavaScript I saw recommendation to use 'for' loop to go via elements of hash collection. I implemented that, but the following code:

    function MyClass(objs)
    {
        var _objs = objs;

        this.showNames = function () {
            var s = "Names: ";
            for (var obj in _objs) {
                s += obj.getName();
            }
            console.log(s);
        };
    }

    function MyObj(name)
    {
        var _name = name;

        this.getName = function () { return _name; };
    }

    var mc = new MyClass({ 'M': new MyObj("morning"), 'D': new MyObj("Day") });
    mc.showNames();

gives error:

Uncaught TypeError: obj.getName is not a function

What am I doing wrong?

Thanks!

Community
  • 1
  • 1
Budda
  • 18,015
  • 33
  • 124
  • 206
  • 1
    Highly recommend that you either get in the habit of including a `hasOwnProperty` check with your for...in loops or using `Object.keys(myObject).map` which does it for you. – Jared Smith Oct 10 '15 at 18:54

1 Answers1

1

obj is the key name and not the value

var s = "Names: ";
for (var obj in _objs) {
    s += _objs[obj].getName();
}
console.log(s);
FuzzyTree
  • 32,014
  • 3
  • 54
  • 85