1

Suppose I have a class such as this in python:

class Table:
    """Class which provides users"""

    def __init__(self):
        self.users = [None] * 8
        pass

    def __len__(self):
        return 8

    def __getitem__(self, key):
        # get users inside a table by index
        if not 0 <= key <= 7:
            raise IndexError("User must be an integer in the range: 0-7.")
        if self.users[key] is None:
            self.users[key] = User(self, key)
        return self.users[key]

If I were to now create an instance of table and reference table like this:

my_table = Table()
my_table[3] # indexes the third user of the table, behind the scenes python creates a new User object and puts it into the list at index 3 if there is nothing at index 3 already

The User class isn't relevant to what I'm trying to do. I'm wondering if there's a way to make the number-indexable parts of a javascript object initiated from a class into dynamically generated properties of that object.

In short, I want to do this (or something that achieves the same functionality):

myTable = new Table()
myTable[3] // or even myTable.3 if that's a thing

I'm sorry for no sample JavaScript code, I just have no idea where to start on the functionality I'm trying to achieve.

fahim545
  • 149
  • 1
  • 6
  • Javascript now has [proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy), which would let you do this (albeit with a bit more work). – Mark Oct 18 '21 at 02:51
  • https://stackoverflow.com/q/32622970/14950361 – pxDav Oct 18 '21 at 02:52

0 Answers0