thednp
thednp

Reputation: 4479

Javascript: Access function within deep object on parse

I have an object

var object1 = {
  object2: {
    function1: function(a, b, c, d, e) {
      //do some stuff with those parameters
      console.log('values are ' + a + ' ' + b + ' ' + c + ' ' + d);
    },
    function2: object1.object2.function1(2, 3, 4, 5)
  }
}

Why the line function2: object1.object2.function1(2, 3, 4, 5) line throws Uncaught TypeError: Cannot read property 'object2' of undefined and how can I make that work?

UPDATE: the answer is marked.

Thank you

Upvotes: 1

Views: 60

Answers (4)

Jan Turoň
Jan Turoň

Reputation: 32912

If you want function2 as shorthand for function1 called with predefined arguments, you might use bind:

object1.object2.function2 = object1.object2.function1.bind(null, 2, 3, 4, 5)

if you need context, replace the null for object1.object2

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386654

var object1 = {
    object2: {
        function1: function (a, b, c, d, e) {
            //do some stuff with those parameters
            console.log('values are ' + a + ' ' + b + ' ' + c + ' ' + d);
        },
        function2: function () { this.function1(2, 3, 4, 5); return this; }
    }.function2()
}
object1.object2.function1(9, 8, 7, 6, 5);

Upvotes: 1

Margus
Margus

Reputation: 20048

Following would work:

var object1 = {
  object2: {
    function1: function(a, b, c, d, e) {
      //do some stuff with those parameters
      console.log('values are ' + a + ' ' + b + ' ' + c + ' ' + d);
    },
    function2: function(a, b, c, d, e) {
        object1.object2.function1(2, 3, 4, 5);
    }
  }
}
object1.object2.function2();

Basically at the time that you want to call object1 it does not yet exist. This is the reason you get this error. I just delayed this, by inserting it to a function and explicitly calling it later.

Note that javascript does no parameter checks, just fails if they mismatch.

Upvotes: 1

David Votrubec
David Votrubec

Reputation: 4156

Because scope in which function2 is defined does not contain definition of object1. Then when you try to access object1.object2 it throws error because object1 is not defined

Upvotes: 1

Related Questions