![](/img/trans.png)
[英]Why does `Array.length`, `Function.length`, `String.length`, etc return 1?
[英]How to override Function.length to return the length of an array, in strict mode
我正在尋找一種方法來覆蓋JavaScript中的Object的.length屬性。
我目前在parent.properties.objects數組上有一個包裝器
(父用於使代碼在上下文中更具可讀性)
這是基本結構:
(父變量在命名空間中定義並初始化)
var parent = function () {
this.properties = {
objects: [];
};
};
(function () {
"use strict";
objects = function () {
如果沒有傳遞參數,則假設get
if (arguments.length === 0) {
var _objects = parent.properties.objects;
return _objects;
修改或過濾對象
} else if (arguments.length > 0) {
...
}
};
這會創建一個object.prototype(不是[prototype])變量並添加方法長度()
objects.prototype.length = function () {
var length = parent.properties.objects.length;
return length;
}
錯誤
objects.prototype.__proto__.length = function () {
var length = parent.properties.objects.length;
return length;
}
parent.objects = objects;
})();
假設我已正確理解您的問題,以下代碼可能會幫助您:
function MyObject() {
this.myActualData = [];
}
Object.defineProperty(MyObject.prototype, 'length', {get: function() {
return this.myActualData.length;
}});
這是一個使用它的例子:
var x = new MyObject();
x.myActualData.push("Hello");
x.myActualData.push("World");
x.length; // is 2
注意:這僅適用於ecmascript 5及更高版本的瀏覽器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.