1

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

thednp
  • 4,401
  • 4
  • 33
  • 45

4 Answers4

1

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

David Votrubec
  • 3,968
  • 3
  • 33
  • 44
1

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.

Margus
  • 19,694
  • 14
  • 55
  • 103
1
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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169