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

2
  • 1
    Make bigRow a property of someContainerObject and you can say functionCall(someContainerObject[table.row]). Commented Jun 10, 2017 at 7: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]). Commented Jun 10, 2017 at 7:43

3 Answers 3

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] )
Sign up to request clarification or add additional context in comments.

Comments

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/

Comments

0

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

function ( this[ table.row ] )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.