Get the reference name of an object?

后端 未结 2 1473
后悔当初
后悔当初 2020-12-22 07:04

I have an object inside another object:

function TextInput() {
    this.east = \"\";
    this.west = \"\";
}

TextInput.prototype.eastConnect = function(obje         


        
相关标签:
2条回答
  • 2020-12-22 07:23

    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.

    0 讨论(0)
  • 2020-12-22 07:31
    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.

    0 讨论(0)
提交回复
热议问题