如何在严格模式下重写Function.length以返回数组的长度

时间:2022-03-09 17:26:46

I am looking for a way to override the .length property of an Object in JavaScript.

我正在寻找一种方法来覆盖JavaScript中的Object的.length属性。

I currently have a wrapper on parent.properties.objects array

我目前在parent.properties.objects数组上有一个包装器

(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

如果没有传递参数,则假设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()

这会创建一个object.prototype(不是[prototype])变量并添加方法长度()

  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;
})();

1 个解决方案

#1


3  

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.

注意:这仅适用于ecmascript 5及更高版本的浏览器。

#1


3  

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.

注意:这仅适用于ecmascript 5及更高版本的浏览器。