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 the textInput1
variable 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 .name
property so it's accessible later:
function TextInput(name) { // Added constructor parameter.
this.name = name; // Save name for later use.
this.east = null;
this.west = null;
}
TextInput.prototype.eastConnect = function(that) {
this.east = that;
that.west = this;
}
textInput1 = new TextInput("textInput1"); // Pass names to constructor.
textInput2 = new TextInput("textInput2");
textInput1.eastConnect(textInput2);
puts(textInput1.east.name); // Now name is available.
(As a bonus I also made a few stylistic changes. It's better to initialize east
and west
to null
rather than an empty string ""
. null
better represents the concept of "no connection yet". And consider that
as an alternate for object
.)
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:
alert(textInput1.east === textInput2 ? "it worked" : "uh oh");
This tests that the connection was made and uses the ternary ? :
operator to print one of two messages.
puts(textInput1.east.name)
This gives an undefined because JS is trying to find an object called name inside east, which does not exist. If you want to pass the name then I think you'll need to do it by passing a string. You can think about creating a property name inside east that may give its name in string. But if there are a lot of objects and you're looking for name of each then you can't go on doing this. Bad OO practice.
精彩评论