比方说,我有一个JavaScript对象:设置length属性
function a(){
var A = [];
this.length = function(){
return A.length;
};
this.add = function(x){
A.push(x);
};
this.remove = function(){
return A.pop();
};
};
我可以用它像这样:
var x = new a();
x.add(3);
x.add(4);
alert(x.length()); // 2
alert(x.remove()); // 4
alert(x.length()); // 1
我试图让.length
不是一个函数,所以我可以像这样访问它:x.length
,但我没有得到这个工作的运气。
我想这一点,但它输出0
,因为这是的A
在时间长度:
function a(){
var A = [];
this.length = A.length;
//rest of the function...
};
我也试过这样,它也输出0
:
function a(){
var A = [];
this.length = function(){
return A.length;
}();
//rest of the function...
};
怎么办我得到x.length
以输出对象内部数组的正确长度?
下面是关于[试图继承阵列(http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/)一些有趣的阅读。 – Pointy