Search code examples
javascriptobjectgetter-setter

Override a object's bracket [index] getter/setter in JavaScript?


I am currently building a Doubly linked list implementation.
What I am trying (or hoping) to do, is to use a setter / getter to set elements in the list, just like you would in an array:

var index = 5;
list[index] = node_x;

However, I can't just use this syntax, because the nodes aren't technically properties of the list.
Think of the list as 2 hooks. These 2 hooks are connected to 2 ends of a chain, but you can only access the those 2 connecting chain-links (And their siblings through them).
The rest of the chain-links are not properties of the list. That's why I need to override the implementation of the brackets [] on my object, if possible.

My (simplified / shortened) code is:

(function () {
    "use strict"
    window.List = function () {
        var Length //Etc
        return {
            //Getter / Setter example.
            get length() {return this.Length;},
            set length(n) {this.Length = n;},
            //Function example.
            insertBeginning: function (newNode) {/*  */},
            insertEnd: function (newNode) {/*  */},

            //Index getter / setter attempt.
            get i(index){ console.log(index); },
            set i(index, node){ console.log(index); }
        };
    };

}());

var list = new List();
list.length = 10 //This works just fine
console.log(list.length) // Returns 10, like expected.

Now, what I was trying to do with the i getter/setter, is to set elements like this:

var index = 5;
list.i(index) = node;

But of course, that doesn't work, since:

  1. i is not a function;
  2. I can't assign variables to a function, obviously.

I could of course just use a function to set the elements:

list.setAtIndex(index, node);

But I'd prefer to override the array notation for the object, somehow.

So, my question is, is that possible? And if so, could I get some hints? My search attempts have only returned resources like this, I know how getters / setters work by now.


Solution

  • Aside from this being a bad idea, it's simply not possible.