Click to See Complete Forum and Search --> : OOP Question...advanced ish
Scriptage
05-01-2003, 05:12 AM
hey,
I'm writing some oo code and am wondering if there is a way to get an objects variable name, ie,
function someobj(id){
this.id=id;
this.displayId = displayId;
return this;
}
function displayId(){
with(this);
<---- I would like to be able to get the variable that the object is stored in (ie objX)---->
}
var objX = new someobj('0909');
Thanks in advance
Carl
Falconix
05-01-2003, 07:08 AM
You could always just make a member of the class that holds the object's name, and have it set during the constructor, as a second arguement.
Scriptage
05-01-2003, 09:37 AM
I thought as much,
Thanks for your time
Regards
Carl
Scriptage
05-01-2003, 10:02 AM
Just came up with this code...it's sloppy but does the job.
Not sure about cross browser compatibility, but this seems to work well in IE. It is dynamic...just uses an eval to create a new object and sets varname as the variable name holder.
Could you please check it for cross browser compatibilty Dave?
This could be useful.
function display(){
with(this);
document.write("<b>Variable: </b><i>"+this.varname+"</i><br /><b>First name:</b><i>" + this.firstname + "</i><br><b>Last name:</b><i>" + this.lastname + "</i>");
}
function func1(firstname, lastname){
this.firstname = firstname;
this.lastname = lastname;
this.display = display;
return this;
}
function obj(varname, the_object,args){
eval(varname + " = new " + the_object +"(" +args +")");
eval(varname+".varname = ' "+varname+" ' ");
return this;
}
obj('person2',func1,"'Carl','Bates'");
person2.display();
Vladdy
05-01-2003, 12:17 PM
Why an object needs to know the name of it's instance when all the information stored in it is available through this :rolleyes: :confused: :D
Scriptage
05-01-2003, 01:16 PM
say I have a function defined as this.display = display;
function somefunc(){
with(this);
document.write("<a href='#' onClick='"this.display"'>clicky</a>");
}
the above doesn't work!!!!!!
where as:
function somefunc(){
with(this);
document.write("<a href='#' onClick='"+this.varname+".display();'>clicky</a>");
}
would work!
That's why
Regards
Vladdy
05-01-2003, 01:34 PM
If your object is associated with a HTML node (expanding it's functionality), you create the instance of the object within such node:
with(document.createElement('a'))
{ myExtension = new myExtensionObject();
onclick = function () { this.myExtension.processOnClick(); return false;};
}