0

I'm trying to assign an object value to a variable that is defined later in my code (in other words, assigne the value to an address), such as:

var memory;

var object = {};

object.mem = memory;

memory = 'hop';

console.log(object.mem);

would return 'hop'

Nate
  • 7,606
  • 23
  • 72
  • 124
  • Primitives like strings are immutable, and passed by just plain old value, so you don't have a reference to the variable, you just set `object.mem` to `undefined`, and changing the variable later doesn't affect that at all. There's really no way to do what you're expecting here – adeneo Jun 05 '15 at 21:10
  • Possibly related: http://stackoverflow.com/questions/6605640/javascript-by-reference-vs-by-value – disappointed in SO leadership Jun 05 '15 at 21:11
  • I assume that there is a reason why you can't leave out `memory` and simply assign "hop" directly to `object.mem`? – talemyn Jun 05 '15 at 21:11
  • @adeneo So there is no pointers in javascript? – Nate Jun 05 '15 at 21:12
  • @talemyn Yes, my code is far more complex but I simplified it here... – Nate Jun 05 '15 at 21:13
  • 1
    @ncohen No, JavaScript doesn't have pointers. The closest equivalent would be defining a [getter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)/[setter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) -- `var object = { get mem() { return memory; }, set mem(value) { memory = value; } };` – Jonathan Lonowski Jun 05 '15 at 21:14

2 Answers2

1

You cannot do it with a primitive directly but you could create an object that acts as a pointer which contains the value. You end up with an extra layer of indirection but that might meet your needs. e.g.

var memoryPointer = {
    value : null
};

var object = {};

object.mem = memoryPointer;

memoryPointer.value = 'hop';

console.log(object.mem.value);
bhspencer
  • 13,086
  • 5
  • 35
  • 44
-1

To make object.mem == hop, I have a few answers
1.

var memory;

var object = {};

object.mem = memory;

memory = 'hop';
object.mem = memory;
console.log(object.mem);

Because when you assigned object.mem = memory, memory was undefined.
So you could just assign memory before the object.