i constructed a nested object below:
var outerMost = {
inner1: {
innerCall: alert( "i'm the call from inner1" ),
inner2: {
innerCall: alert( "i'm the call from inner2" ),
inner3: {
innerCall: alert( "i'm the call from inner3" ),
inner4: {
innerCall: alert( "i'm the call from inner4" ),
inner5: {
innerCall: alert( "i'm the call from inner5" ),
}
}
}
}
}
};
All i want is to hear the call form inner4 by using this:
outerMost.inner1.inner2.inner3.inner4.innerCall();
But i got calls form every inner alert and was threw an error message pointing to the last expression from the debugger:
Property 'innerCall' of object #<Object> is not a function
What’s wrong with my outerMost?
Note: I’m not going to keep repeating your entire object literal, I’ll just use an abbreviated form…
Each time you said this:
You weren’t creating a property
innerCallthat was thealert()function, you were creating a propertyinnerCallthat was assigned the result of actually calling thealert()function at that moment. The return fromalert()isundefined.So nesting that structure five levels deep called
alert()five times all in the process of creating your object, but the actualinnerCallproperties were all set toundefined. So then this:Was like saying
undefined();– which of course doesn’t work.What you need is for
innerCallto reference a function which in turn callsalert():That is more or less equivalent to doing this:
(Note that in the object literal
myInnerCallFunction1does not have parentheses so it is a reference to the function rather than executing the function.)