OOP question
OOP question
How can an object refer to itself? I tried to use "this" like I would in Java because I saw it done in the documentation for "unref" in the ObjectOrientedProgramming section, but the interpreter said it was an undeclared variable.
-
- Site Admin
- Posts: 6384
- Joined: Wed May 18, 2005 4:50 pm
- Location: Yale University School of Medicine
- Contact:
Re: OOP question
Read the documentation of unref again and you will see that the examplebhalterm wrote:I tried to use "this" like I would in Java because I saw it done in the documentation for "unref" in the ObjectOrientedProgramming section, but the interpreter said it was an undeclared variable.
shows "this" being used within the template, i.e. in that example it is a
private member of the object. Trying to refer to it in a statement that lies
outside of the object will produce an error message. I suppose you could
declare "this" as public, but offhand I don't see the utility of top level
invocations of "this" when any objref that points to the object should
suffice to refer to that object.
Sorry, I was a little vague. I am trying to write a proc within the object that calls another object's proc with itself as one of the arguments. It's a common idiom in Java, so I was inclined to find a way to do this just out of habit. I can certainly find another way to do it. If I were to declare "this" as a private member of the object, is there an easy way to initialize it to refer the enclosing object?
-
- Site Admin
- Posts: 6384
- Joined: Wed May 18, 2005 4:50 pm
- Location: Yale University School of Medicine
- Contact:
object reference: this
Declaring it should be enough--see page 383 of The NEURON Book.bhalterm wrote:If I were to declare "this" as a private member of the object, is there an easy way to initialize it to refer the enclosing object?
Example:
Code: Select all
begintemplate Foo
public myname
objref this
proc init() {
myname()
}
proc myname() {
print "I am ", this
}
endtemplate Foo
NUM = 3
objref fap[NUM]
print "at creation"
for i=0,NUM-1 fap[i]=new Foo()
print "check existing"
for i=0,NUM-1 fap[i].myname()
-
- Site Admin
- Posts: 6384
- Joined: Wed May 18, 2005 4:50 pm
- Location: Yale University School of Medicine
- Contact:
Right. So simple, yet, now as I think about it, so easy to overlook. Reading your original
question, I just assumed that you had declared "this" inside the template, and then tried
referring to it from outside--but that should probably have generated an error msg stating
that "this" is not a public member of the object class.
question, I just assumed that you had declared "this" inside the template, and then tried
referring to it from outside--but that should probably have generated an error msg stating
that "this" is not a public member of the object class.