Learning JavaScript and DOM with Console
Thứ 5, 10:30 AM Ngày 05/08/2010, số lần xem 223, Lập trình web
In this tutorial, you are going to learn what a console is, and more importantly, how you can leverage it to learn JavaScript and DOM quickly. So let’s get started.
Console?
A console is not a specific project or a command-line terminal, nor is it a Xbox 360 or PS3 (though learning JavaScript and DOM on a game console will definitely be awesome
). It is a separated window in a browser that let you inspect all kinds of information about JavaScript objects and DOM objects of the displaying web page, and it exposes an object of the same name (i.e. console) to that page, whose methods can be called to output information of your choice to the console window.
What’s Wrong with alert() and My Home-made log()?
You might ask, “I can display all sorts of things with alert(), what’s the point of console?” It’s true that alert() is a quick-and-dirty way to display variables, but it has a major problem: it steals focus, which will render it useless when mouse interaction or keyboard interaction is involved. That’s not the end of the story, alert() is only good at displaying primitive variables(i.e. strings, numbers, booleans), when trying to display an object, you will be prompted with something like “[object Object]“.
“Fine, I’ll write a custom log() function, which will nicely convert all kinds of variable into meaningful strings and inserts them directly into the document, so it won’t interfere with any interactions. Done, no console is needed.” If that’s what you are thinking, well, I wish things could be that easy, but converting objects into meaningful strings is not an easy task. You’ll have to establish a sophisticated logic, which deeply recursively iterates objects (which may also contain objects) to capture their inner structures, and displaying these structures is not an easy task too.
What Makes Console So Different?
A picture is worth a thousand words. So let me show you a couple of snapshots. I’ll use Google Chrome to demonstrate console, you can access it by pressing Ctrl + Shift + I, and then click the “Console” tab (the last one).
Console is a Separated Window
Which means it will not interfere with mouse interaction or keyboard interaction, and it doesn’t “pollute” the page.

Console Can Also Dock to the Main Window
If you don’t have dual monitors, this is the way to go.

Console Displays Objects Tree-like
Objects are displayed tree-like, and properties can be toggled.

Console Has Access to All Variables Defined by the Environment and You
This is the coolest feature of console. It gives you full access to the page.

Console Auto-completes Your Typing
So that you can focus on experimenting, and don’t have to spend too much time on typing.

Console Indicates DOM Elements Visually
This is another cool feature of console. Move your mouse over the DOM element in the console, it will be highlighted in the page. So it’s a strong indication that what DOM element it actually refers to.

Console Exposes a console Object
We will look at this object in great detail later on.

Cute, But I Don’t Use Google Chrome
Don’t worry, Google Chrome isn’t the only browser that supports console. But even if you do use Google Chrome, the following sections still help, because you may want to learn different quirks about different browsers, and knowing how to invoke console on those browsers become important.
Safari
Safari5 has an almost identical console, which can be accessed by pressing Ctrl + Alt + C. The one in Safari4 isn’t as helpful. It displays objects as “[object Object]“. A workaround is introduced in the section labeled “Opera, IE”.

Firefox
Firefox has an excellent extension called Firebug, which is arguable the father of modern developer tools. You should first installed it in Firefox, after which, you can access it from the status bar. To see more about a DOM element in the console (e.g. the document object in this example), you need to click on it, and Firebug will switch to another tab, which contains all properties of that DOM element.

Opera, IE
Opera has its own developer tool called Dragonfly which needs installation, and IE8′s integrated developer tool can be accessed by pressing F12. Both of them aren’t as helpful as previous ones. They don’t highlight DOM elements, no auto-completion what so ever, and worst of all, they display objects as “[object Object]“. For IE6 and IE7, Microsoft released a developer tool called Internet Explorer Developer Toolbar, which unfortunately doesn’t have a console at all.
But don’t worry, Firebug to the rescue! Fortunately, Firebug team created a cross-browser version of Firebug that works with all major browsers. It’s called Firebug Lite. It has a bookmarklet version and a script file version. Bookmarklet lets you invoke the console on any website, whereas script file lets you invoke the console before your code sends variables to it.

Since Firebug Lite is not part of browser, it isn’t “privileged”, which means it can’t do things like getting the line number of a pariticular function call, profiling for a chunk of code and some other things that need low level support, but they don’t cover the fact that Firebug Lite has a great console.
OK, I’m Sold. How do I Use it Exactly?
If you want to examine a JavaScript object or a DOM element, console is the definite way to do it. As you may have guessed, there are two ways to use a console: you either type directly in it, or your use the console object in your code.
The latter is desirable, because you may forget a particular characteristic the test code demonstrates, in which case you can recall it quickly just by reviewing that code, which is saved in file. Typing directly in console is more like a one-shot deal, and it’s only suitable for very trivial code.
The console Object
If a browser supports console (either natively or via Firebug Lite), it will expose an object called console to your JavaScript code. You can invoke its various methods to display various aspects of information of your code to the console window.
Let’s see what methods the console object has and what they do.
First, we should establish a test environment:
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>Test</title>
<!-- Include Firebug Lite if necessary -->;
<!-- <script src="https://getfirebug.com/firebug-lite.js" type="text/javascript"></script> -->
<!-- Your test file goes here -->
<script src="test.js" type="text/javascript">
console.log()
This is the method you will use most of the time. It will output its arguments to the console, and yes, it accepts arbitrary number of arguments. When displayed, they are separated by space. It also supports printf-like string substitution patterns, which should be familiar to C/C++ programmer.
var s = 'string';
var i = 1;
var f = 3.2;
var o = {a: 1, b: 2, c: 3};
console.log('string', s, 'integer', i, 'float', f, 'object', o);
console.log('string %s integer %i float %f object $o', s, i, f, o);

console.info() / console.warn() / console.error() / console.debug()
These methods are basically the same as console.log(), but they assign messages to different categories (e.g. warning category, error category, as their names suggest). console.info() is identical to console.log() in Google Chrome, for it doesn’t have an “info” category. console.debug() is designed to also output an hyperlink which points to the line where it was called, and it’s also identical to console.log() in Google Chrome, which outputs this hyperlink for all log()-like methods.
var s = 'string';
var i = 1;
var f = 3.2;
var o = {a: 1, b: 2, c: 3};
console.debug('string', s, 'integer', i, 'float', f, 'object', o);
console.info('string', s, 'integer', i, 'float', f, 'object', o);
console.warn('string', s, 'integer', i, 'float', f, 'object', o);
console.error('string', s, 'integer', i, 'float', f, 'object', o);

console.assert()
This method acts a bit like assertions in unit testing. It tests whether the first argument is true or not. If it is, it will do nothing, otherwise, it will output an error message consisting of the other arguments.
console.assert(true, 'this will output nothing');
console.assert(false, 'this will generate an error message');

console.dir() / console.dirxml()
These two methods are designed to display JavaScript objects and DOM elements, respectively, as lists. They are identical to console.log() in Goole Chrome. We will use Firebug as an example.
var o = {a: 1, b: 2, o: {a: 1, b: 2}};
console.log(o);
console.dir(o);
var div = document.createElement('div');
div.innerHTML = 'content';
console.log(div);
console.dirxml(div);

console.trace()
This method will outputs the stack of function calls at the point where it is called. Confused? It’s clearer with a code example. Notice that console.trace() is not well-supported by Google Chrome (which just outputs the caller function), so we will still use Firebug as an example.
function a() {
b();
}
function b() {
c();
}
function c() {
console.trace();
}
a();

console.group() / console.groupEnd() / console.groupCollapsed()
These methods are designed to structure messages. They indent messages generated between console.group() and console.groupEnd() and nest them in a block that can be toggled. You can pass arbitrary number of arguments to console.group(), which will be displayed as the title of the block. console.groupCollapsed() is the same as console.group(), except that it collapses the block by default, and it’s only supported by Firebug.
console.group('string methods');
console.log('substr', 'string'.substr(1,3));
console.log('substring', 'string'.substring(1,3));
console.groupEnd();
console.group('array methods');
console.log('slice', [1,2,3,4,5].slice(1,3));
console.log('splice', [1,2,3,4,5].splice(1,3));
console.groupEnd();

console.time() / console.timeEnd()
As you may have guessed, these methods measure how much time have elapsed between their invokings. Many developers use them to test function performence. They accept an argument as an ID, so that console.timeEnd() knows which timer created by console.time() to stop, and it also gets displayed as a title before the actual time.
function fn1() {
var fn = function() {};
}
function fn2() {
var fn = new Function();
}
console.time('fn1');
for(var i = 0 ; i < 1000 ; ++i) {
fn1();
}
console.timeEnd('fn1');
console.time('fn2');
for(var i = 0 ; i < 1000 ; ++i) {
fn2();
}
console.timeEnd('fn2');

console.profile() / console.profileEnd()
These methods turn on/off the JavsScript profiler, which scrutinizes function calls in great detail. Firebug has a clearer profile result in my option. console.profile() accepts an argument as the title of the profile result.
function fn1() {
var fn = function() {};
}
function fn2() {
var fn = new Function();
}
console.profile('fn');
for(var i = 0 ; i < 1000 ; ++i) {
fn1();
}
for(var i = 0 ; i < 1000 ; ++i) {
fn2();
}
console.profileEnd();

console.count()
This method will count the number of times it have been called. It accepts an argument as an ID to support multiple countings.
function a() {
b();
c();
console.count('a()');
}
function b() {
c();
console.count('b()');
}
function c() {
console.count('c()');
}
a();
b();
c();

console.exception() / console.table()
Firebug supports two addtional methods that are not supported by Google Chrome or Safari. console.exception() will output its first argument as an exception object along with its function call stack, and the other arguments constitute the message. console.table() will output its first argument, which should be array of arrays or list of objects, in a tabular layout. It also accepts a second argument, which specifies columns and/or properties to be displayed. See more of console.table() here.
Since these methods are not widely supported. You should avoid use them.
function a() {
b();
}
function b() {
c();
}
function c() {
throw new Error('something is wrong');
} try {
a();
} catch (e) {
console.exception(e, 'error catched');
}

var a = [
['a1', 'a2', 'a3'],
['b1', 'b2', 'b3'],
['c1', 'c2', 'c3']
];
console.table(a);
var o = {
div: {tag: 'div', content: 'div content'},
p: {tag: 'p', content: 'p content'},
span: {tag: 'span', content: 'span content'}
};
console.table(o);

Conclusion
Console can be a great tool for your to learn JavaScript and DOM. If you haven’t used it before, you should start now. It will accelerate your learning speed, and it is worth the time to get familiar with console. That’s all. Thanks for reading this tutorial.
Nguồn tuttoaster.com