设置JavaScript对象的长度属性 [英] Set length property of JavaScript object
问题描述
假设我有一个JavaScript对象:
Let's say I have a JavaScript object:
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
,但我没有运气让它工作。
I was trying to make .length
not a function, so I could access it like this: x.length
, but I've had no luck in getting this to work.
我试过这个,但输出 0
,因为这是 A
的长度当时:
I tried this, but it outputs 0
, because that's the length of A
at the time:
function a(){
var A = [];
this.length = A.length;
//rest of the function...
};
我也尝试了这个,它还输出 0
:
I also tried this, and it also outputs 0
:
function a(){
var A = [];
this.length = function(){
return A.length;
}();
//rest of the function...
};
如何获得 x.length
到输出对象内部数组的正确长度?
How do I get x.length
to output the correct length of the array inside in the object?
推荐答案
因为当你调用 a.length
,你正在返回一个函数。为了返回输出,你必须实际调用该函数,即: a.length()
。
Because when you call a.length
, you're returning a function. In order to return the output you have to actually invoke the function, i.e.: a.length()
.
顺便说一句,如果你不想让length属性成为函数而是实际值,你需要修改你的对象以返回属性。
As an aside, if you don't want to have the length property be a function but the actual value, you will need to modify your object to return the property.
function a() {
var A = [];
this.length = 0;
this.add = function(x) {
A.push(x);
this.length = A.length;
};
this.remove = function() {
var removed = A.pop();
this.length = A.length;
return removed;
};
};
这篇关于设置JavaScript对象的长度属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!