javascript - Get the reference name of an object? -
i have object inside 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) // gives undefined.   in last statement want print out object's reference name, in case: textinput2.
how do that?
objects exist independently of variables reference them. new textinput() object knows nothing textinput1 variable holds reference it; doesn't know own name. have tell name if want know.
store name explicitly. pass name constructor , store off in .name property it's accessible later:
function textinput(name) {                  // added constructor parameter.     this.name = name;                       // save name 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 constructor. textinput2 = new textinput("textinput2");  textinput1.eastconnect(textinput2);  puts(textinput1.east.name);                 // name available.   (as bonus made few stylistic changes. it's better initialize east , west null rather empty string "". null better represents concept of "no connection yet". , consider that alternate object.)
this raises question of why want print name in first place, though. if goal able in general variable (for debugging purposes, say), ought rid of notion. if you're trying test connection made properly, consider this:
alert(textinput1.east === textinput2 ? "it worked" : "uh oh");   this tests connection made , uses ternary ? : operator print 1 of 2 messages.
Comments
Post a Comment