将属性对象的选定对象从原型推入数组

Pushing selected objects of objects of properties from a prototype into an array

本文关键字:对象 原型 数组 属性      更新时间:2023-09-26

先为标题道歉。

我有这个原型,它还没有被实例化:

noZoomzoom对象将在实例化时被对象填充。

我想从我的Persona构造函数的所有属性中将noZoom对象中的所有对象推入propertiesToIlluminate array

function Persona() {
    this.headArea = {
        noZoom: {},
        zoom: {}
    }
    this.torsoArea = {
        noZoom: {},
        zoom: {}
    }
    this.arm = {
        noZoom: {},
        zoom: {}
    }
    this.leg = {
        noZoom: {},
        zoom: {}
    }
    this.pelvis = {
        noZoom: {},
        zoom: {}
    }
    this.abdomen = {
        noZoom: {},
        zoom: {}
    }
    this.illuminate = function() {
        var propertiesToIlluminate = [],
            prop, illuminateInternal, i = 0,
            delay = 100,
            intervalId;
        for (prop in //what to put here//) {
            propertiesToIlluminate.push(prop);
        }
    }
}

试试这个:

for (prop in this) {
    if (this[prop].noZoom) {
        for (key in this[prop].noZoom) {
            if (this[prop].noZoom.hasOwnProperty(key)) {
                propertiesToIlluminate.push(this[prop].noZoom[key]);
            }
        }
    }
}

保留一个属性列表,然后将其缩减以构建数组可能是有意义的。比如:

function Persona() {
  var properties = ["headArea", "torsoArea", "..."];
  // ...
  this.illuminate = function() {
    var self = this;
    var propertiesToIlluminate = properties.reduce(function(arr, propName) {
      var noZoom = self[propName].noZoom;
      for (var prop in noZoom) {
        if (noZoom.hasOwnProperty(prop)) {
          arr.push(noZoom[prop]);
        }
        return arr;
      }
    }, []);
  }
}

同样的列表也可以用于初始化对象,迭代它以构建初始状态。

for (var i=0; i<properties.list; i++) {
  this[properties[i]] = {noZoom: {}, zoom: {}};
}

如果需要,它也可以暴露在原型上,这样其他代码可以很容易地获得所有属性的列表。