0
var myObject = {
    sub: {
        myFunction: function() {
            console.log('check');
        }
    }
}

var callFn = 'sub.myFunction'; // I want it to solve it here, whats going wrong?

myObject[callFn](); // Works, but not with 'sub.myFunction'
myObject.sub.myFunction(); // This works ofc.

I need a generic solution. Can someone explain why the sub.myFunction does not work? Does anyone have a workaround to solve this?

Sam
  • 7,252
  • 16
  • 46
  • 65
  • 1
    Let's ask the other way around: Can you explain why you thought that `'sub.myFunction'` would work? – Tomalak Dec 27 '15 at 12:20
  • I don't think you can use a `[]` to do a double access (accessing `sub` from `myObject` and `myFunction` from `sub`). You may use two `[]`, one for each access. – Felypp Oliveira Dec 27 '15 at 12:22
  • 1
    *"Can someone explain why the sub.myFunction does not work?"* Because `myObject` doesn't have a property called `sub.myFunction`. It has a property called `sub`, which refers to another object, which has a property called `myFunction`. – T.J. Crowder Dec 27 '15 at 12:22
  • 1
    And, by extension: What do you indent to do in the first place? Because the question does not make a lot of sense, i.e. this solves no problem that you should have. If you have that problem, its likely that there's something wrong in your approach itself. – Tomalak Dec 27 '15 at 12:24
  • @T.J.Crowder The other question does not really address why a simple string like `"sub.myFunction"` does not work to access the property in js. I think that's the OP's main question here. – just.another.programmer Dec 27 '15 at 12:29

1 Answers1

0

The . character is a valid part of a property name in javascript as long as you enclose it in quotes.

What that means to you:

  • myObject["sub.myFunction"] - looks for a property named sub.myFunction on myObject. It does not look for a property named myFunction on the sub property of myObject.

  • myObject.sub.myFunction - does not have the . in quotes so it's treated as a property accessor. That means we look for a myFunction property on the sub property of myObject.

just.another.programmer
  • 8,579
  • 8
  • 51
  • 90