22 lokakuuta, 2014

Part 2 JS Workbench

Workbench for JavaScript coding in 'strict mode'

How to start coding in strict mode JavaScript. In 'strict mode' there is very much different rules than "normal" JavaScript. But it is worth of effort to learn new skills right now, especially if you just started to learn JavaScript. Always good to have external script file, do not code in HTML document at all, if you can. Make sure you have this kind of script tag in your HTML5 document:

<script src="js/main.js" onerror="alert('Load Err: ' + this.src)">

There is special onerror -handler that shall reveal if problem is already in the file load, or url of the file. You can't find the error from the file if it is not even loaded. Next, make a "main.js" -file into folder named "js" and start writing some JavaScript in it, like this example. First line is always this, and last line is always that (3rd line).

var xyz = function () { 'use strict'; // this is wrapper start ...
       // Only 'strict mode' -experiments here !
}(); // strict mode wrapper end

This is a recommendation: Use "function format" of 'use strict' -sentence.

1. First there is there clauses: (); - So everything is isolated from global window object

2. Anonymous function is next and with extra clauses it is runned into memory. 
This is a wrapper for our app.

function () {} ();

3. Next big thing, and first thing in actual code block is the 'strict mode' -message that tells the browser to be strict with everything. If you put 'strict mode' -message only inside of functions, all global area will not be in 'strict mode'. 
This is the best practise nowadays, as far as I know.

4. Next put some error codes to help with finding where the errors are hiding: 
Those alert -messages can be changed to use anything to get the messages into your debugger, if you use one.

Adding Try - cach() - finally - blocks to catch some error messages.

try {  /*debug area*/
window.onerror=function(msg,Url,Ln,ch){
alert("Window error:\n" + msg + "\nURL: " + Url + "\nLine: " + Ln+"/"+ch);
};
///////////// TEST AREA START - DO NOT EDIT BEFORE THIS ///////////

// Only 'strict mode' -experiments here !

var put = function(w) {alert('Message: ' + w ); };
put("Hello World"); // Testing 'put' -function

///////////// TEST AREA END - DO NOT EDIT AFTER THIS ///////////
 } catch (e) { //This is runned only if some error has been thrown
        throw e; //Sending error to window.onerror -handler for line number.
} finally { //This block is runned every time.
//alert("'main.js' loaded in memory."); 
 } // try

There you are. Nothing to do with actual 'strict mode' -code yet, but we are coming to it...
Next thing is to try some interesting experiments with this workbench. 
Maybe we add a little self made unit testing method and...
That will be explained on next page.