Jump to content

Functions and Bracket Notation


S Murder

Recommended Posts

Can you give an example? Bracket notation is typically only used for array syntax, assuming you're talking about [square brackets]. Give an example of referencing the property using the notation you're talking about.

Link to comment
Share on other sites

Can you give an example? Bracket notation is typically only used for array syntax, assuming you're talking about [square brackets]. Give an example of referencing the property using the notation you're talking about.
I'm told every Object in JS is an associative array of functions and properties, and I heard everything that can be referenced with dot notation can be referenced with bracket notation too.var anchorTag = document.getElementsByTagName("a")[0];//dot notation for propertiesanchorTag.href//bracket notation for propertiesanchorTag["href"]//dot notation for functionsanchorTag.toString()//bracket notation for functions?????
Link to comment
Share on other sites

I'm not sure, you might be able to. If you can, the syntax would be like this:anchorTag["toString"]()If your situation is that you have a function name in a string and want to execute the function, there is another way to do that as well. If you have some Javascript code in a string, you can use eval. Here is a simple function call:

var js = "toString";eval("anchorTag." + js + "()");

Or a more complex example:

<html>  <head><title>test</title></head>  <body>  	<script type="text/javascript">	var array_name = "test_array";	var element0 = "val1";	var element1 = "val2";	var element2 = "val3";	var js = "var " + array_name + " = new Array();\n";	js += array_name + "[0] = \"" + element0 + "\";\n";	js += array_name + "[1] = \"" + element1 + "\";\n";	js += array_name + "[2] = \"" + element2 + "\";\n";	alert("Code to run:\n" + js);	eval(js);	alert("Array has " + eval(array_name + ".length") + " elements");	alert("First element: " + test_array[0]);	</script>  </body></html>

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...