有没有办法在JavaScript中创建类似数组的对象,而不使用内置数组?我特别关注这样的行为:
var sup = new Array(5);
//sup.length here is 0
sup[0] = 'z3ero';
//sup.length here is 1
sup[1] = 'o3ne';
//sup.length here is 2
sup[4] = 'f3our';
//sup.length here is 5
Run Code Online (Sandbox Code Playgroud)
我在这里看到的特殊行为是sup.length更改而没有调用任何方法.我从这个问题中了解到,在数组的情况下,[]运算符会被重载,这就解释了这种行为.有没有一种纯粹的JavaScript方式来复制这种行为,或者语言是不是足够灵活?
根据Mozilla文档,正则表达式返回的值也可以用这个索引做一些时髦的事情.用普通的javascript可以实现吗?
这就是我现在正在做的事情.
var foo = function() {
var x = someComplicatedComputationThatMayTakeMoreTime();
this.foo = function() { return x; };
return x;
}
Run Code Online (Sandbox Code Playgroud)
它工作,但只有当foo被调用为这样的函数
foo();
Run Code Online (Sandbox Code Playgroud)
但是如果我想将它称为具有值的正常变量呢?我可以修改代码
var foo = function() {
var x = someComplicatedComputationThatMayTakeMoreTime();
this.foo = x;
return x;
}
Run Code Online (Sandbox Code Playgroud)
这将允许我只将它作为一个函数调用一次,然后作为常规变量调用它.但它仍然不是我想要的.如果它意外地再次被调用为函数,它会变得复杂,并返回错误.
这在JavaScript中是否可行?
顺便说一句,这是针对Chrome/Firefox扩展,因此IE兼容性并不重要.
使用toString结束因为getter不允许我重新定义整个属性,所以函数必须与之关联.并且toString具有更清晰的语法.