Page 1 of 1

Strange behaviour from a javascript object

Posted: 2019-05-14, 17:43
by vannilla
In one of the extensions I'm maintaining, there is an object whose behaviour is strange. Printing it with console.debug() shows that it has a number of properties, but trying to access them with obj[key] returns undefined.

Basically (simplified examples to keep them short):

Code: Select all

'use strict';

let obj = {};

// Fill the object with the rest of the extension's code

console.debug(obj)
// |- Object { a: 1, b: 2, c: 3}

let key = 'a';
console.debug(obj[key])
// |- undefined

console.debug(obj.hasOwnProperty(key))
// |- false
What might cause this?
This piece of code is executed inside an anonymous function, which exports an object that access this "private" obj variable through a number of closures.

Re: Strange behaviour from a javascript object

Posted: 2019-05-14, 18:06
by adesh
What is the type of keys? String - did you check that they are not "double quoted"?

Re: Strange behaviour from a javascript object

Posted: 2019-05-14, 18:54
by vannilla
The keys are strings taken from a JSON object.
I'm not sure what you mean by "double quoted", can you expand on it?

Re: Strange behaviour from a javascript object

Posted: 2019-05-15, 00:30
by Moonchild
Your simplified method works just fine if you try it in scratchpad.

Re: Strange behaviour from a javascript object

Posted: 2019-05-15, 13:02
by vannilla
The examples in the OP aren't meant to be executed, they're just to illustrate the problem.

Anyway, I probably discovered what was up:
the whole thing uses closures a lot, and in fact the object was a non-local variable for a number of functions.
I had been defining functions using the form "function foo(args) {...}", which apparently were saving the initial state of the object (i.e. the empty object), so even if said object was modified somewhere, those functions would keep accessing something empty.
Changing the definition to a variable assigment (let foo = function (args) {...}) seems to have fixed it, as in this case a new function is created whenever the assignment is met, meaning it will save the current state of the object inside the closure (which stops existing when the block ends.)

It's quite the corner case, but I should keep it in mind.

Re: Strange behaviour from a javascript object

Posted: 2019-05-15, 13:55
by Moonchild
vannilla wrote:
2019-05-15, 13:02
The examples in the OP aren't meant to be executed, they're just to illustrate the problem.
The examples did not illustrate the problem since they didn't provide a proof of concept to illustrate the behavior.
vannilla wrote:
2019-05-15, 13:02
the whole thing uses closures a lot, and in fact the object was a non-local variable for a number of functions.
Well in that case it's expected. Non-local objects become immutable copies unless you specifically make them variable.