2
$\begingroup$

Say I have a programming language that can support user-defined classes (all debates over whether OOP is actually good aside) - how do I store instances of these user-defined classes when executing a program?

If I'm interpreting my language, what data structures do I use?

If I'm compiling my language, what do I write to memory and where?

$\endgroup$
2
  • 3
    $\begingroup$ I think this could possibly be made into a good question, but it seems to be a bit broad as currently stated. $\endgroup$
    – Isaiah
    May 16, 2023 at 22:53
  • $\begingroup$ Given that there are three question marks, I agree $\endgroup$
    – Seggan
    May 16, 2023 at 23:04

1 Answer 1

2
$\begingroup$

Functions and Prototypes

This is what JavaScript does. Consider this modern TypeScript class:

class Normal {
  x: number;

  constructor(x: number) {
    this.x = x;
  }

  getDoubleX(): number {
    return this.x * 2;
  }
}

This is roughly equivalent to this older JavaScript:

function Normal(x) {
  if (!(this instanceof Normal)) {
    throw new TypeError("Class must be constructed with 'new'");
  }
  this.x = x;
  return this;
}

Normal.prototype.getDoubleX = function getDoubleX() { return this.x * 2; };

Then, when the new keyword is used, something like this happens behind the scenes:

// var obj = new Normal(2);
var obj = Object.create(Normal.prototype);
obj = Normal.call(obj, 2);

This allows for some really interesting stuff at runtime, like changing what class an object belongs to or conditionally installing extension methods.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged .