question about recursion and OO javascript

L

lielar

Hi

I'm writing a javascript class object that creates objects of itself.
Take for example

function One(x){
this.x = x;
}

One.prototype.addOne = function(x) {
this.extra=x;
}

One.prototype.getOne = function() {
return this.extra;
}

One.prototype.print() = function() = {
return this.x.toString();
}

Then I want to retrieve it where you can retrieve many levels of
'extra'. How do you make a loop to keep on looking in to a child
values of printValus? How do you solve the problem of 'this' in this
scenario? Wouldn't there be a problem with memory leak?

Cheers
Patrick
 
R

RobG

Hi

I'm writing a javascript class object that creates objects of itself.
Take for example

function One(x){
this.x = x;
}

One.prototype.addOne = function(x) {
this.extra=x;
}

One.prototype.getOne = function() {
return this.extra;
}

One.prototype.print() = function() = {
Oops...--------------^^--------------^

return this.x.toString();
}

Then I want to retrieve it where you can retrieve many levels of
'extra'.

I don't know what you mean by "levels of extra". Do you mean assign
an object to "x"?
How do you make a loop to keep on looking in to a child
values of printValus?

You use recursion: test the argument, if it's an object, use for..in
to loop over all the properties and for each one, call the function
again. Otherwise, return its toString() value. If you don't know
what type of object you are dealing with, you may want to check if
it's an Array, Function, RegExp, etc.

You probably also want to collect the results of recursion and return
a single, collated string value.

How do you solve the problem of 'this' in this
scenario?

You haven't identified a problem with 'this'.
Wouldn't there be a problem with memory leak?

There may be a problem with too much recursion, but that normally
occurs way beyond what is reasonable in most cases.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top