0

I have an object

bigRow = {size:'long', color:'pink'};

Let's say I have another object table, which has row property, e.g.

table = {
    row: 'bigRow',
    column: 'smallColumn'
};

Can I pass the object 'bigRow' as a parameter to a function using table's property value as a reference?

Can I write something like

function ( table.row )

that would work like

function ( bigRow )

Even though both turn out to be function( bigRow ), the former comes out as a string without any connection to the object

Arthur Tarasov
  • 3,517
  • 9
  • 45
  • 57
  • 1
    Make `bigRow` a property of `someContainerObject` and you can say `functionCall(someContainerObject[table.row])`. – nnnnnn Jun 10 '17 at 07:42
  • 1
    You usually can (because JavaScript is so flexible/unstructured) but it sounds like a really bad idea. Usually there's a better value to store in `table` (e.g. instead of a string you could store the object itself) or if you really need to look things up by name, you use an object like this: `rows = { bigRow: { ... } };` then you can do `func(rows[table.row])`. – melpomene Jun 10 '17 at 07:43

3 Answers3

2

I don't think it's possible that way. However, you could put bigRow inside another object like so:

var rowTypes = {
    bigRow : {size:'long', color:'pink'},
    //other rows if necessary...
}

And then access that member of the rowTypes object using the string as an identifier:

function ( rowTypes[table.row] )
Botimoo
  • 599
  • 6
  • 16
1

Yes, you can but you should set your object as property of current document using "this" keyword.

<!DOCTYPE html>
<html>
 <body>
  <div id="demo"></div>
 </body>
</html>

<script>
 this.bigRow = {size:'long', color:'pink'};
 this.table = {
    row: 'bigRow',
    column: 'smallColumn'
 };

 function myFunction(myRow){
  document.getElementById('demo').innerHTML = myRow.size;
  console.log(myRow);
 }

 myFunction(this[table.row]);
</script>

https://jsfiddle.net/0p5afpj9/

burak
  • 3,839
  • 1
  • 15
  • 20
0

I came across an answer to a similar question. Apparently, this will work if both objects are global:

function ( this[ table.row ] )
Arthur Tarasov
  • 3,517
  • 9
  • 45
  • 57