在JavaScript中覆盖对象的括号[index] getter / setter? [英] Override a object's bracket [index] getter/setter in JavaScript?

查看:67
本文介绍了在JavaScript中覆盖对象的括号[index] getter / setter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在构建双重链接列表实施。

我正在尝试(或希望)做的是使用setter / getter来设置列表中的元素,就像在数组中一样:

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;

但是,我不能只使用这种语法,因为节点在技术上不属于list。

将列表视为2个钩子。这两个钩子连接到一个链的两端,但你只能访问那两个连接的链节(和它们的兄弟姐妹通过它们)。

其余的链节不是属性的列表。这就是为什么我需要在我的对象上覆盖括号 [] 的实现,如果可能的话。

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.

现在,我试图用 i getter / setter,设置如下元素:

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. 不是函数;

  2. 我无法将变量赋给显然是一个函数。

  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.

所以,我的问题是,这可能吗?如果是这样,我可以得到一些提示吗?
我的搜索尝试只返回了资源这样的,我知道getters / setters到现在是如何工作的。

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.

推荐答案

除了这是一个坏主意,它根本不可能。

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

这篇关于在JavaScript中覆盖对象的括号[index] getter / setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆