0

In node.js (Javascript) I have two classes, class mainclass and subclass, where subclass inherites from mainclass.

In an other module (other class, other .js file) i have an array of objects from class mainclass:

myArray[0] = new mainclass(); 
myArray[1] = new mainclass();
//etc..

On runtime, i want to create a new subclass object, and set its reference to the one in myArray[0], so that myArrayis not changed, but myArray[0] then returns the new subclass object.

And i want to do this in the mainclass, so that the array is not changed, but the reference in the array points now to an other object (the new subclass object). In fact i want to do something like

this = new subclass();

in a method in mainClass

mainClass.prototype.changeType = function(){
 this = new subclass();
}

which of course doesnt work because you cant assign value to this.

8
  • What does the array looks like ? Commented Nov 11, 2016 at 12:08
  • 1
    You can't assign to the this keyword Commented Nov 11, 2016 at 12:09
  • So you have an array of mainclass and want to change that to an array of subclass? Commented Nov 11, 2016 at 12:13
  • You can't replace a "new" with another "new". Javascript is not as powerful as C, sorry :-| Commented Nov 11, 2016 at 12:20
  • @schroffl i basically want the references in the array pointing to other objects than before Commented Nov 11, 2016 at 12:24

1 Answer 1

1

You could "simulate" pointers if you are ready to access your objects through indexes. As you can see below, whatever object reference is at index 0, it remains available :

function Person (name) { this.name = name; };
Person.prototype.whoami = function () { return this.name };
memory = [];
memory.push(new Person("Hillary Clinton"));
memory[0].whoami(); // "Hillary Clinton"
memory[0] = new Person("Donald Trump");
memory[0].whoami(); // "Donald Trump"

Good luck though... x-D

Sign up to request clarification or add additional context in comments.

7 Comments

I dont want to change the array, but the references stored point to other objects than before..
@Lucker10 If you always access an object through its index, replacing it with another should be harmless.
yeah.. in C it would work easy. I thought maybe JS is so hacky that you can set an objects reference by (new mainclass).setReference(..) or something
@Lucker10 As far as I know, there is no such possibility.
@Lucker10 Javascript is not design to perform this kind of stuff, and that's fine. If you really need to touch the memory you can still choose another tool like C. Otherwise there are plenty of ways to bypass your problem while keeping a clean and elegant code :-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.