1

I have a function like this:

this.doStuff({
    'testkey': {
        testfunction: function() {
            // will return testfunction
            console.log(Object.keys(this));
        }
    }
});

Is there are a way of getting testkey within the testfunction scope?

The Object.keys(this) will return testfunction.

Colin Rauch
  • 455
  • 1
  • 5
  • 16

3 Answers3

2

The JavaScript this keyword is a bit of an unusual beast — it's going to change depending on how a function is called, and most of the time, this will refer to the function it's inside. In this scenario, that's just testfunction, so naturally it's going to give you only the results local to that function.

There's various tutorials on understanding this available:


In your scenario, Object.keys() takes an object and returns its keys. If you want the keys of your object, you need to give it that (I've renamed your variables though):

var foo = {
    'key': {
        func: function() {
            console.log(Object.keys(foo)); // <------
        }
    }
};
Community
  • 1
  • 1
doppelgreener
  • 5,752
  • 8
  • 42
  • 59
2

if you know which method to call inside the javascript object, then you can do so.

You can preserve the scope of caller using apply or call method

function doStuff(ob){
  ob[Object.keys(ob)]['testfunction'].call(ob);
}

doStuff({
    'testkey': {
        testfunction: function() {
            // will return testkey
            console.log(Object.keys(this));
        }
    }
});
A.T.
  • 18,248
  • 7
  • 39
  • 59
1

you simply can do :

var object = {
    'testkey': {
        testfunction: function() {
            // will return testfunction
            console.log(Object.keys(object));
        }
    }
};

because inside the function scope you can see the global var 'object'

Oriel.F
  • 390
  • 2
  • 17