0

So i have this program, it took me a while to figure out how to create objects dynamically. Based on other stats. Anyhow, i was wondering why this actually works. It makes one object for each td. Eg, Currently it has 100 td elements. I wanted to be able to seperate information for each td and be able to acess it based on the tds id #. of which that works fine.

Why are the objects accessible as just like any other object?

Im kind of puzzled by the part of why it works. I know that it does lol.

Anyhow here is my code... It placed at the end of the html document right before /body.

<script>
    (function (){
    var list = document.getElementsByTagName("td");
    var number = 0;
    var text = '';
    text += '<script>';
    text += 'var plots = {\r';

    while (number <= list.length - 1) {
        text += number + ' : {\rstamp : 0\r';
        if (number >= list.length - 1) {
            text += '}}\r';
            number++
        } else(text += '},\r');
        number++
    }
    text += '</\script>';
    document.write(text);
    })();
</script>

So again, if you can help me understand, Why is it that these work as if i hard coded the objects in???

Basically, i made a script that makes a script... kinda odd to me.

Btw the \r's are only there to make it more readable when looking ad the source code in the console. no other reason. they are not needed of course.

like to know why 3dgoo removed (function (){ was there and is supposed to be there otherwise it does not work... Thanks.

  • 2
    You should fix your indentation of braces and blocks and use more meaningful variable names than `xxx` so your code is easier to decipher. – Patashu Jun 03 '13 at 04:11
  • You are writing it to the document inside of a script tag, same as if you had "hard coded" it. And in my opinion, this is a pretty bad way of doing whatever you are trying to accomplish. – teynon Jun 03 '13 at 04:13
  • Btw. i need this because i make a table that goes with these objects. They are giving ids as numbers. I needed the table cells to cooresponds directly with an object so i can access a key:value pair that relates to/hold information about the cell. – Brent Smith Jun 03 '13 at 04:14
  • Tom i dont see how it is a bad way... The point being ok its written inside a script tag. But isnt script parsed and all that at runtime? so these objects were or were not parsed with the origional code at runtime? if they werent they why do they work... lol – Brent Smith Jun 03 '13 at 04:17
  • It's bad to use `document.write()` http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – Alan Jun 03 '13 at 04:19
  • @BrentSmith: It is bad for multiple reasons. One of the biggest ones for me is the readability of the code. I have to read javascript inside of javascript to be able to debug this. (Plus, no code highlighting if you like that. Why can't we just create the global variable and then assign the new elements? – teynon Jun 03 '13 at 04:22
  • How is it bad? It doesn't overwrite anything in my code. Im guessing because i used it inside of an immediately invoked function expression? – Brent Smith Jun 03 '13 at 04:24
  • Tom, as i said though I needed to use objects that are numbered that directly corresponds to ids that were numbers in cells. because other parts of this project also work in a dynamic manner just like this snippet. so rather than having to hard code each instance of a new oject (item) which are items that are using in the program. Items as in items in a game. i could not think of an easier way to do this. so to add me items i just add them to the oeject that holds a list of all the objects (identified by numbers). so its easily extendible without having to add or edit 20 lines for one thing.. – Brent Smith Jun 03 '13 at 04:29
  • @BrentSmith, why are you arguing with people trying to help you? – 3dgoo Jun 03 '13 at 04:33
  • @3dgoo Im not arguing... I asked a question and people are criticizing the way i did something.... rather than helping me understand my origional question. The qeustion isnt about the code itself. its only there to give people an idea of what it is im talking about. – Brent Smith Jun 03 '13 at 04:37
  • @BrentSmith: http://jsfiddle.net/KmKzL/ The reason it works is pretty simple based on what I said in the comment or the answer currently on this page. See the fiddle for just one way that would be better than what you are doing. – teynon Jun 03 '13 at 04:45
  • Nevermind... and yes the fiddle works as needed. – Brent Smith Jun 03 '13 at 05:09
  • your code isn't doing anything with the `id` property, and @Tom's code isn't doing anything with the `td` value either. He's doing the exact thing your code is doing. Generating a number from 0 to the the number of td elements in the page-1. – Alan Jun 03 '13 at 05:10
  • @Alan a table is made in a similar fashion as the object with the same numbering :) i edited that out after i realized what i said lol. – Brent Smith Jun 03 '13 at 05:12
  • Well so far alan has technically answered my question. Tom;s code works for my existing code as is. And i thank you for the fiddle that is a better way or doing what i needed. I try to write all my own code before looking for better ways to do the same thing. I feel i myself learn better doing it that way. Also helps me understand what the code is doing as well. Just my way or doing things i guess. I was not aware of your method Tom hence why i did not use it. Now its something new in my arsenal. – Brent Smith Jun 03 '13 at 05:20

1 Answers1

3

Why is it that these work as if i hard coded the objects in???

The reason why it works, is how the browser interacts with script tags, and how the browser interprets javascript.

When the browser encounters a script tag, it's default behavior is to execute the code inside it.

This allows you to do some powerful and expressive things, but can also be a major source of headaches.

What you are doing, is essentially modifying the DOM, the underlying object that represents the HTML structure. You're writing HTML to it (in this case a <script> tag), which causes the browser to properly render the content. Since the browsers behavior is to execute script when it encounters a <script> tag, it executes your javascript. When it executes your javascript, it creates a global variable named "plot" which can then be accessed in the global namespace.

This lets you do the exact same thing, but without document.write.

var plot = (function () {
    var list = document.getElementsByTagName("td");

    var plots = {};

    for(var i = 0; i < list.length; ++i) {
      plots[i] = {'stamp': 0};    
    }

    return plots;
})();

This plunker shows an interactive example of the above code. Note that the script tag comes in the body tag.

Edit to add, from Comment:

Yes javascript is parsed at runtime, however when the DOM is reevaluated, that causes any new javascript to be executed. Code that has already executed, or events that have already fired won't execute again.

Alan
  • 42,055
  • 16
  • 107
  • 130
  • I like this answer... but the thing is though javascript is parsed at runtime correct? so is the code that i dynamically create parsed too? cause if not then it would not make sense to me that the objects would be accessible by the rest of the code in the document. – Brent Smith Jun 03 '13 at 04:31
  • Ah, well i was not saying at all that the method of doing what i did was flawed. There is always a better way to do anything. Thanks for the nice code though :). So what if the number of plots change after execution? Would the plots object change with them? from what i see they would... and would still be accessible just like they are now? – Brent Smith Jun 03 '13 at 04:43
  • Btw using your code. At the beginning or end of my document does not give my code acess to the plots oject... says its not defined. – Brent Smith Jun 03 '13 at 04:47
  • As Alan posted in his link: document.write `executes where encountered: it cannot inject at a given node point`. And since javascript is "running" when it is writing that code, yes, it is parsed. – teynon Jun 03 '13 at 04:47
  • Yeah i know it cannot inject at a node point... My understanding is essentually is is injected exactly where the document.write is. because that is what is happening for me. Immediadly below the document.write statment is where my var plots object is located. least in the console. – Brent Smith Jun 03 '13 at 04:54
  • @BrentSmith: note that the `plots` object is assigned to a global variable called `plot` – Alan Jun 03 '13 at 05:01
  • So why does the console say Object {stamp: 0} when it needs to say 0: {stamp :0} apparently there is something not right on your code... cause my code outputs 0:{stamp:0}, etc etc – Brent Smith Jun 03 '13 at 05:05
  • @BrentSmith: Click on this link: http://plnkr.co/edit/sidXbZsMrz7W1yF3voAs?p=preview The code outputs exactly what you expect. – Alan Jun 03 '13 at 05:07
  • Alan actually no... the objects have their number inside quotes... hence not what i expect... – Brent Smith Jun 03 '13 at 05:17
  • That's because I'm serializing it to JSON to show on the page. `object['1']` is the same as `object[1]` Javascript property names are always strings, because a numerical variable name are illegal. You can't have `var 1foo = 'bar';` – Alan Jun 03 '13 at 05:18
  • I accepted this on the basis that it actually answers my original question of why it works. Thanks for all the code examples though! Even though thats not what the question was about :). alan look at this picture.... http://prntscr.com/180qks and my code as is could not acess your plots object... – Brent Smith Jun 03 '13 at 05:22