Vytautas
Vytautas

Reputation: 462

JavaScript error: property is not defined

I'm a Java programmer experimenting with JavaScript objects. I get an error for this code:

var a = {
    map: new Map(),
    put: function (k, v) {
        map.set(k, v);
    }
}
a.put("key", "value");

Error is: Uncaught ReferenceError: map is not defined

What am I doing wrong?

Upvotes: 0

Views: 1504

Answers (3)

Mamun
Mamun

Reputation: 68933

You have to use object name (a) or this to refer the property like:

a.map.set(k, v);

OR:

this.map.set(k, v);

var a = {
    map: new Map(),
    put: function (k, v) {
        this.map.set(k, v);
    }
}
a.put("key", "value");

Upvotes: 2

Max Baldwin
Max Baldwin

Reputation: 3472

First off, welcome to the dark side. To answer your question, you have to reference the map key in your object declared as a as a.map. So like this.

var a = {
    map: new Map(),
    put: function (k, v) {
        a.map.set(k, v);
    }
}
a.put("key", "value");

Upvotes: 1

musicfuel
musicfuel

Reputation: 1680

With literal objects you are not able to access the keys directly at definition time because they do not yet exist. You need to use execution of the function combined with the this keyword to refer to own properties

var a = {
    map: new Map(),
    put: function (k, v) {
        this.map.set(k, v);
    }
}
a.put("key", "value");

Upvotes: 2

Related Questions