I am looking for a way to override the .length property of an Object in JavaScript.
I currently have a wrapper on parent.properties.objects array
(parent is used to for the code to be more readable in context)
This is the basic structure:
(parent variable is defined in namespace and intialized)
var parent = function () {
this.properties = {
objects: [];
};
};
(function () {
"use strict";
objects = function () {
If no argument is passed, assume get
if (arguments.length === 0) {
var _objects = parent.properties.objects;
return _objects;
modify or filter objects
} else if (arguments.length > 0) {
...
}
};
this creates a object.prototype (not [prototype]) variable and adds the method length()
objects.prototype.length = function () {
var length = parent.properties.objects.length;
return length;
}
Error
objects.prototype.__proto__.length = function () {
var length = parent.properties.objects.length;
return length;
}
parent.objects = objects;
})();
Assuming I've understood your question correctly, the following code might help you:
function MyObject() {
this.myActualData = [];
}
Object.defineProperty(MyObject.prototype, 'length', {get: function() {
return this.myActualData.length;
}});
And here's an example of it in use:
var x = new MyObject();
x.myActualData.push("Hello");
x.myActualData.push("World");
x.length; // is 2
Note: this will only work on ecmascript 5 and above browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With