Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override Function.length to return the length of an array, in strict mode

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: [];
  };
};

wrapper

(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;
})();
like image 887
gjmwolmarans Avatar asked Oct 21 '22 20:10

gjmwolmarans


1 Answers

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.

like image 158
kybernetikos Avatar answered Oct 27 '22 09:10

kybernetikos