Lucker10
Lucker10

Reputation: 504

create subclass object with reference to existing object

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.

Upvotes: 0

Views: 151

Answers (1)

user1636522
user1636522

Reputation:

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

Upvotes: 1

Related Questions