0

I'm trying to address a field of an object in javascript from within a function in another field like this:

var binds = {};
var name = 'hi';
binds[name] = {
  foo: [],
  bar: {
    add: function (e) { foo.push (e); }
  }
}

I tried this.foo.push (e) and binding the function with .bind (binds[name]) and .bind (this) but neither of those worked, how can I reference the foo element from with a function in bar?

EDIT:

I'm trying to reference a field which is not on the same object but higher up. So this is different from the linked question.

Evan Davis
  • 35,493
  • 6
  • 50
  • 57
Lev Kuznetsov
  • 3,520
  • 5
  • 20
  • 33
  • Your `bind` approach is correct, only it suffers from the problem mentioned in the duplicate. – Bergi Feb 09 '15 at 22:58
  • While the questions are similar, they aren't the same one. The other question is asking how to initialize a property based off of others. This question is asking how to create a method that references other properties. Very different. Anyway, I answered it below. –  Feb 09 '15 at 23:00
  • There's no JSON there. That's a JavaScript object. – Quentin Feb 10 '15 at 00:06

1 Answers1

0

You can toy with a module pattern to store references to higher-up properties like this:

var binds = {};
var name = 'hi';

binds[name] = (function() {
    var arr = [];
    return {
        foo: arr,
        bar: {
            add: function(e) {
                arr.push(e);   
            }
        }
    }
})();

binds[name].bar.add('test');
console.log(binds[name].foo); //logs ["test"]
  • I need to have the add function deeper, see my code, it's different. This is just the simplest example – Lev Kuznetsov Feb 09 '15 at 22:59
  • Ah, I didn't realize. I'll delete my answer for now and come back later on tonight when I have more time :) –  Feb 09 '15 at 23:08
  • That's kind of what I had, I was hoping there was something less ugly. – Lev Kuznetsov Feb 09 '15 at 23:15
  • Yeah, I don't think there is a less ugly way to do this. There will be other ways to do it, but all of them are eye sores. Unfortunately, there's not a good way to tell an object literal to "go up one level". –  Feb 09 '15 at 23:16