<a href="http://www.micropoll.com/akira/mpview/585320-168921">Click Here for Poll</a><a href="http://www.questionpro.com" title="online surveys">Online Survey</a><BR> | <a href="http://www.micropoll.com" title="Website Polls">Website Polls</a><BR> | <BR><a href="http://www.micropoll.com/akira/MicroPoll?mode=html&id=168921">View MicroPoll</A></div>

Visual Studio 2010!

Read now >

Windows Mobile Development Thoughts

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.
ADVERTISEMENT
ADVERTISEMENT

 

DevSource.com: Your Source for Visual Studio on Facebook
ADVERTISEMENT
Creating Objects in JavaScript
By Jeff Cogswell

Rate This Article: Add This Article To:

Creating Objects in JavaScript - ' Trying out the code'
( Page 2 of 3 )

Trying out JavaScript code

In the past, to try out JavaScript code, people would put the code in an HTML file and then open the HTML file in a browser. To make changes to the code, you had to make the changes inside the HTML file, and then reload the file in the browser.

This approach is still useful, but for debugging code and trying out code snippets, the approach is a bit cumbersome. Instead, there are some tools available that you can use to try out JavaScript code. One tool that I like, unfortunately, doesn't work with Internet Explorer; instead you need FireFox. It's called FireBug. It's probably about the best JavaScript debugging tool I've found. (There's a "Lite" version for Internet Explorer, but I find it's not quite powerful enough.) You can get the tool here.

You can also, with various limitations, use the Windows Script Host, which is built into Windows. To do so, you can just save your JavaScript code in a file with a .js extension, and then run

wscript filename.js

The only caveat is that there are certain objects in JavaScript we've come to expect, such as the alert() function, which are actually part of the browser and not the language itself. To use alert() under WSH, you need to instead call WScript.echo(x). You can do this by writing your own echo function. Thus the preceding code would need an extra function at the beginning:

function alert(x) {
    WScript.echo(x);
}

var a = 10;
function DoSomething(a) {
    alert(a);
} 
DoSomething(a);
alert(DoSomething);

Another option is a quick and dirty HTML file I wrote this morning. You can run this in IE. Here's the code:

<html>
<style>
* {
    font-family:Tahoma;
    font-size:12px;
}
</style>

<script>

    function log(str) {
        if (str != null) {
            document.getElementById("output").innerHTML += str + "<br>";
        }
    }
    
    function dir(x) {
        for (var name in x) { log("[" + name + "] = " + x[name]); }
    }

    function runcode() {
        var sourceElem = document.getElementById("source");
        var source = sourceElem.innerHTML;
        log(eval(source));
        var historyElem = document.getElementById("history");
        historyElem.innerHTML += "<br>";
        historyElem.innerHTML += source;
        sourceElem.innerHTML = ";
    }
    
    function clearOutput() {
        document.getElementById("output").innerHTML = ";
    }
</script>

<body>

<table border="1">
<tr>
<td valign="top" style="width:300px;height:500px;">
<pre id="output">
</pre>
</td>
<td valign="top">
<a href="javascript:runcode();">Run</a>
<a href="javascript:clearOutput();">Clear Output</a>
<br>
<div id="history" style="height:300px;width:300px"></div><br>
<textarea id="source" style="height:200px;width:300px"></textarea>
</td>
</tr>
</table>

</html>

I called this debug.html. Then I opened debug.html in Internet Explorer. A table will be present, and in the lower-right is the place you can type your JavaScript code. To run your code, click the Run link at the top. The output appears in the left column, and your code gets moved to a history box in the upper-right. I've included a "log" function where you can write your variables and such to the output box.

Following is a screenshot showing me typing some code that includes the log function. After I click Run, the output ("10") will appear in the left pane, and my code will be moved to the upper-right pane.

It's quick, it's dirty, and not that great, but it'll get you by for now if you need it.

A function's value

Now back to our earlier question. What is the value of the function? Let's try out the code. Here it is again:

var a = 10;
function DoSomething(a) {
    alert(a);
}
DoSomething(a);
alert(DoSomething);

The third statement calls the DoSomething function, passing in the value of a, which will result in a message box showing the number 10. The fourth and final statement displays the value of the function object. If you run the code in IE, the image to the right shows the box you'll see. (You'll see essentially the same thing in Firefox.)

In other words, the value of the function displays as nothing more than the function and its code. However, that's just the visual representation of the function. The function, being an object, can have additional members. (In fact, there are some built in.) Let's look at that next.

A function's members

Since a function is an object, you can attach additional members to the function. Let's start fresh with some new code:

function FunctionObj() {
    alert('hello');
} 
FunctionObj.a = 10;
FunctionObj.b = 20;
alert(FunctionObj.a);

This code creates a function (or function object, if you will) called FunctionObj. It takes no parameters and just shows a Hello message. Now remember, since JavaScript runs code statement-by-statement, this function object will get created when the function statement runs.

Next comes an interesting line:

FunctionObj.a = 10;

When this line runs, it adds a member variable called a to the FunctionObj object. The next line of code adds another member variable.

So now the function, in addition to having its code, has two member variables. Finally, the code displays an alert box showing the value of the object's a member. (How many alert boxes will you see when you run this code? Only one. If you answered Two, think about why the alert statement inside the function doesn't run in this code snippet.)

Why is all that useful? Let's look at another, slightly more practical example:

function Increment() {
    Increment.value++;
} 
Increment.value = 0;

This code creates a function object called Increment. After creating the function (but not running the function, remember), the code adds a member to the function called value, initializing the value to 0. The code inside the function increments the value. Here's a complete sample that demonstrates the code:

function Increment() {
    Increment.value++;
} 
Increment.value = 0;

alert(Increment.value);
Increment();
alert(Increment.value);
Increment();
alert(Increment.value);

Follow the steps here: The function object is created (but not run), and then a value member is attached. The code displays the value. Then the code finally calls the Increment function, which increments the value. Then the code displays the value again, resulting in a 1 being displayed. Next the code increments again, and then displays again, showing a 2.

This code is only somewhat useful, however, as we only have a single counter. In the world of objects, it would be nice to have multiple counters. That's next.



 
 
>>> More Microsoft Languages Articles          >>> More By Jeff Cogswell