I have an object inside another object:
function TextInput() {
this.east = "";
this.west = "";
}
TextInput.prototype.eastConnect = function(object) {
this.east = object;
object.west = this;
}
textInput1 = new TextInput();
textInput2 = new TextInput();
textInput1.eastConnect(textInput2);
puts(textInput1.east.name) // this gives undefined.
In the last statement I want to print out the object’s reference name, in this case: textInput2.
How do I do that?
Objects exist independently of any variables that reference them. The
new TextInput()object knows nothing about thetextInput1variable that holds a reference to it; it doesn’t know its own name. You have to tell it its name if you want it to know.Store the name explicitly. Pass the name to the constructor and store it off in the
.nameproperty so it’s accessible later:(As a bonus I also made a few stylistic changes. It’s better to initialize
eastandwesttonullrather than an empty string"".nullbetter represents the concept of “no connection yet”. And considerthatas an alternate forobject.)This raises the question of why you want to print the name in the first place, though. If your goal is to be able to do this in general with any variable (for debugging purposes, say), then you ought to get rid of that notion. If you’re just trying to test that the connection was made properly, consider something like this:
This tests that the connection was made and uses the ternary
? :operator to print one of two messages.