How to return an object from a dynamic reference in Javascript?

Asked

Viewed 318 times

2

I need to create a Javascript code that returns an object already created with a dynamic reference by its name/id.

Basically this:

// Define class
function Test(num) {

    this.msg = "Message";   
    this.num = num;

}

// Create objects
var objTest_1 = new Test(1);
var objTest_2 = new Test(2);
var objTest_3 = new Test(3);


// Call objects in loop
for (i = 1; i <= 3; i++) { 
/*
    // Static reference
    alert( objTest_1.msg + objTest_1.num );
    //or
    alert( Object(objTest_1).msg + Object(objTest_1).num );
*/

    // Dinamic reference
    alert( Object("objTest_" + i).msg + Object("objTest_" + i).num );  // Return error "NaN"
}

Ps: In this example I just look for some "Property" of the object, but in my actual code I need to actually return an existing object to call a specific method that it contains.

4 answers

2

The easiest is to use an array:

// Define class

function Test(num) {

    this.msg = "Message";   
    this.num = num;

}

var objetos = [];
objetos.push( new Test(1) );
objetos.push( new Test(2) );
objetos.push( new Test(3) );

for (var i = 0; i < 3; i++) { 
    // ^ IMPORTANTE, faltava o var

    alert( objetos[i].msg + objetos[i].num );
}

  • The big question is that who generates the objects is the framework of the system I’m using, basically I can’t change the way they are built.

  • @lorduakiti this framework creates the objects with var even?

  • @Panther would not know to inform you with full certainty but I believe so!

1


You can use the global object to access variables global dynamically. In the browser the global object is the window (you can use the this also, which references the same global object as the window points out).

// Define class
function Test(num) {

    this.msg = "Message";   
    this.num = num;

}

// Create objects
var objTest_1 = new Test(1);
var objTest_2 = new Test(2);
var objTest_3 = new Test(3);


// Call objects in loop
for (i = 1; i <= 3; i++) { 
    // Dinamic reference
    console.log( window["objTest_" + i].msg + window["objTest_" + i].num );
}

If these objects are declared with var within functions the variables will be associated with what is called Activation Object. But unlike the global object, there is no way to access it, and consequently there is no way to access the variables associated with it.

In this case you have the option to store the objects in an array, as suggested in one of the answers, or use the function eval. Assuming your code is inside an anonymous function:

(function() {
  // Define class
  function Test(num) {

    this.msg = "Message";   
    this.num = num;

  }

  // Create objects
  var objTest_1 = new Test(1);
  var objTest_2 = new Test(2);
  var objTest_3 = new Test(3);


  // Call objects in loop
  for (i = 1; i <= 3; i++) { 
    // Dinamic reference
    console.log( eval("objTest_" + i).msg + eval("objTest_" + i).num );
  }
})()

eval will execute the string you pass as parameter. But beware! The function eval should be used as a last resort and with great caution. Use eval is dangerous because, depending on how you generate the string to be executed, you may end up injecting some malicious script into the user’s machine.

References:

0

I discovered a way to call a javascript object by its id dynamically:

window["objTest_" + 1]

0

You can use the

val()

In practice the val() executes a string as if it were javascript code.

var x = 10;
var y = 20;
var a = eval("x * y") + "<br>";
var b = eval("2 + 2") + "<br>";
var c = eval("x + 17") + "<br>";

var res = a + b + c;

Upshot

200
4
27

http://www.w3schools.com/jsref/jsref_eval.asp

Example using on objects.

var obj = { a: 20, b: 30 };
var propname = getPropName();  //returna "a" ou "b"

eval( "var result = obj." + propname );

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

Browser other questions tagged

You are not signed in. Login or sign up in order to post.