Is there a way to "mirror" properties from one object to another?

3

Let's say I want to do a function type debugText(obj) , this function takes an object as a parameter and shows its properties on the screen, such as game debug screens.

Something like:

function debugText(link,prop) {

  this.TextObject = new Engine.Utils.Text()

  this.link = link
  this.prop = prop

  this.update = function () {
    this.TextObject.setText( this.link[this.prop] )
  }

}

In use:

var texto1 = new debugText(Player,"speedX")
var texto2 = new debugText(Missle,"positionY")

It works very well for these two examples and when I need to know other things when testing the code, more if I want to access something like:

Player.skin.currentAnimation.frame.frameInfo.index ?

I could add more parameters to the function and then see how many of them are being used and create the this.update based on it.

But this function will always be limited to a fixed number of properties and even though I will never use more than 5 I still do not like how this function works: link

EDIT

The question is: do you have a correct way of "mirroring" the properties of an object or updating them with a function call regardless of how many depth levels of Object.prop1.prop2.pro3... you have to update ?

For you to have an idea how many ways I have already thought about how to do this is the last

debugText(Player.skin.currentAnimation.frame.frameInfo,"index")

This also works BUT is it really okay to pass an object with properties and pass only the last property as a string just to use computed property names to access this value?

    
asked by anonymous 30.10.2016 / 07:02

1 answer

3

One suggestion:

var obj = {
    foo: 12345,
    bar: {
        teste: {
            aninhado: {
                chave: 6789
            }
        }
    }
};

function mostrarProps(obj, props) {
    var valores = props.map(function(prop) {
        if (typeof prop == 'string') return obj[prop];
        // else...
        var key, val = obj;
        while (key = prop.shift()){
            val = val[key];
        }
        return val;
    });
    document.body.innerHTML = valores.join('<br>');
}

mostrarProps(obj, ['foo', ['bar', 'teste', 'aninhado', 'chave']]);

The idea is to have a function that accepts an array of properties to look for. In this array you can have _String_s to directly access properties on a first level, or an array with "the path" to go until you reach the value you want.

jsFiddle: link

However:

I think it would be simpler to use console.log() to know object values if it is to debug, or even JSON.stringify() that transforms the object into a string and thus creates a static image of how the object was at a given height.

    
30.10.2016 / 09:02