1

Learning Javascript; I want to reduce memory usage by using a prototype function (#2). However, in order to pass relevant state/arguments from an instance to the prototype function, I need to create another function (#1).

I understand that in Javascript, the object method (#1) would be created for each Row instance, negating memory savings from re-using the prototype function (#2). Memory savings would also be negated if I replaced function #1 with a closure.

Is there a way for each Row object to call the prototype function on the Row's own unique state while still minimizing memory usage?

function Row(data) { 
  row = Object.create(Row.prototype);
  row.state = data;

  //#1
  row.showInstanceState = function() {
    Row.prototype.showState(this.state);
  };

  return row; 
}

//#2
Row.prototype.showState = function(info) {
    console.log(info);
}

let example = new Row(2);

/*
If function #1 didn't exist, the call 
below saves memory but we have explicitly pass 
in an instance's data at the moment of the call. 
*/
example.showState(example.state);

//The call style below is desired, but requires function #1, which would not optimize memory usage.
example.showInstanceState();
AMemberofDollars
  • 331
  • 2
  • 14
  • 1
    I'm not understanding something, why can't you just put `showInstanceState` on the prototype? – CertainPerformance Nov 26 '19 at 00:13
  • I'm not understanding why you would use `prototype` at all, in a case where you have access to just add to the constructor. By the way, JavaScript constructors return `this` by default. Ridiculous design. – StackSlave Nov 26 '19 at 00:29
  • Your use of prototypes and constructors is totally off. How did your code look without them? – Bergi Nov 26 '19 at 00:35

1 Answers1

1

When using the new keyword, you're basically running your Row() function with this pointing to a newly (and automatically) created object and returning that object. So your function constructor should look like this:

function Row(data) { 
  this.state = data;
}

The object and its prototype will already be assigned when using new.

Then you can add your prototype methods:

Row.prototype.showInstanceState = function() {
  console.log(this.state);
};

When you call methods as members of an instance, this will always point to the instance object (unless you're using call or apply), so this.state will point to the instance own property (which you created in the constructor).

let example = new Row(2);
let example2 = new Row(5);

example.showInstanceState(); // 2
example2.showInstanceState(); // 5
ezakto
  • 3,174
  • 22
  • 27
  • I'll try to come up a better (but likely still contrived) example that better reflects a nuanced situation I'm dealing with. I also lack the proper terminology to describe my issue. My head should be clearer tomorrow after I get some sleep. – AMemberofDollars Nov 26 '19 at 03:25