Simply JavaScript Core Library Confusion: Init

UPDATE

FIXED
Thanks anyway everyone, and I am looking forward to spending my time learning from the SitePoint titles and Forums!

Early on in this title Simply JavaScript it is explained that in order to modify elements and HTML in the document, the script must not be executed until the entire document and it’s elements are loaded or else an error occurs, and the author tells me to use the Init function.

However, it is not explained well how to do this, and I continue to receive the error:

Uncaught TypeError: Cannot read property ‘innerHTML’ of null

I am only on chapter 3 and cannot complete any examples on my own because I do not understand the Core library, how to include it, how to use init, etc. So I am reading but not able to try any examples for myself.

Can anyone help me?

Oh yes, just like anyother language, I expect blocks… but wow, was this a fun one. However, I had a breakthru and hopefully you can tell me the difference in what I found.

The example (which I don’t believe requires Core):


var target = document.getElementById('berenger');
alert(target.nodeName);

What I don’t see in there yet is where to put that. Before using the Core (or any other library, like jQuery which also does this), to get the above code to work (assuming you have the element with id=“berenger” of course in your HTML), you’ll put the <script> tag either after that element, or just right before the closing body tag.

First… To let you know what I was doing during that next quote from you about the berenger thing was just the random code I was using to test the core thing, but to help me help you help me, LOL, I shortened the code to what you just saw in the last post. Luckily the whole time tho I had core connected correctly, just not seeming to get it to work. I even get the next couple of pages where it goes into get by tag, and get by class and changing class, etc. but since I couldn’t connect to the core, I was like, ok… what’s up. Because when I make functions standalone on my libs.js file, they work fine. so, I was stumped. Ok, so now explaining that… brings me to what I found with you awesome help.


I believe when he introduces the whole init() stuff (page 59), he’s hoping you are remembering pages 16-17.

Now since the Core.start code looks for an inner function called init, you’ll need to change libs.js to


var someObject {
	[b]init: function()[/b] {
	    alert("Hello!");
	}
};
Core.start(someObject);

Which you can check by looking at the Robot example on page 59.

Ok, do, I tried that… and, no luck. However, when looking at page 59 along with skipping forward to stripytables to see how the .js was connected and the one thing in both of the examples that mine, nor the example of your section adding the init: part, was the = sign that would go after someObject.


var someObject =
{
	init: function() 
	{
		alert("Hello!");
	}
};
Core.start(someObject);

OMG Putting in the = sign fixed it… It works now. However, I can see why I would have never got that. In the whole talk about the different ways you can write a function, I thought you didn’t need one. But is that because it is an object, and because it is an object it needs the equals sign?


If that version all works, then something you can do for fun to test is make this change in Core:


Core.start = function(runnable)
{
  Core.addEventListener(window, "load", runnable.[b]hello[/b]);
};

and then change libs.js to this


var someObject {
	[b]hello: function()[/b] {
	    alert("Hello!");
	}
};
Core.start(someObject);

YES! With the equals sign, it works great. This is one of those, I just have to memorize or use this template from now on until it is memory… LOL

The reason (I think) why Core looks for the init() function in the object (instead of just the Object directly) is, it shouldn’t work without stating a function in the Core.start code… someObject, or Robot, or whatever aren’t functions themselves but merely Objects who contain functions. So I believe the reason Core has

Core.addEventListener(window, “load”, runnable.init);

is because you have to tell it an actual function to run (and calling the Object by itself won’t do that… the object just holds a bunch of functions together under a name). And init() throughout the book is set up in such a way that it sets up any “global” (not really, but used by the other functions) variables and sets up the event listeners, who then call all the other functions inside your Object.

And I don’t think he mentions why they do it this way, but this is a form of namespacing in Javascript, as recommended in I think chapter 10 of Javascript: the Definitive Guide by Flanagan. Meaning, your object has an init() and someone else’s also has a function named init(), but that’s ok because yours is someObject.init() (or whatever) while theirs is theirObject.init() and the JS interpreter in the browser can see those aren’t the same function despite having the same name. Same goes for variables. This keeps stuff out of the window (global) scope.

OH, ok… so, using the new example where we changed init: to hello in both places, the hello in the core calls the function hello: back in the libs.js to keep the flow going… or trickle down as I think of it. step by step I guess.

OK, now up until I have my next block… LOL… I will see if I can get ahold of that book… The Definitive Guide if I can also. However, what addons for firefox to you recomend for my javascript learning process.

Ok, thanks.

Was this ever answered. I am basically in the same position. I am not getting an error yet, however I am confused on how to use the core.js library. I get the concept of everything, but, since being new to javascript, I am not getting the jist of how to connect to it and use it correctly. There are no real instructions on how to use it.

Any help would be awesome.

Thanks

James.

Been ages since I looked into this book and I am no Javascript expert myself, but my understanding is that whenever you create an object and want something to happen as soon as the page is loaded, you will add a function that will have the code with the changes and code that you want to use This function will called init and belongs to the object.

Then, you use Core.Start(nameOfObject) which will look into the objects properties and methods, and find the one named “init” and then execute the code in that method.

But, of course, in order to do so, the browser needs to know what Core.Start does… The code for this function is in an external file. Its name is core.js. You need to link to it before writing any Javascript code if you’re going to use any function listed there.

So, if you’re keeping your core.js file in the same folder than your html, add

<script type=“text/javascript” src=“core.js”></script>

in the header area of your html, and make sure that it loads before any code that you create and that uses any of its functions.

I assume that the core.js file is with the examples that you can download when you buy the book.

ok, with the idea that I understand linking the core.js file, but in this example, I just copied the part that I am needing from it specifically which was:

	var Core = {};
	
	Core.start = function(runnable)
	{
	  Core.addEventListener(window, "load", runnable.init);
	};

Now, using one html file example, and using the tips you used, I came up with this:

<head>
<title>Tag Name Locator</title>
<!--<script type="text/javascript" src="core.js"></script>-->
</head>
<body>
	<h1 id="berenger">
	Sniper (1993)
	</h1>	
	<script type="text/javascript">
	<!-- Hide from HTML
	// code from core.js
	var Core = {};
	
	Core.start = function(runnable)
	{
	  Core.addEventListener(window, "load", runnable.init);
	};
	// end of core.js
	
	// Test Function
	var SayId =
	{	
		init: findId() 
		{
		var target = document.getElementById("berenger");
		alert(target.nodeName);
		}
	};
	// End of Test Function
	
	Core.start(SayId);
	
	// End Hiding -->
	</script>
	
</body>
</html>

Am I on the right track here? And, is the point to always connect to this start code with everything I do? I ask because I am only just in the 2nd and 3rd chapters and want to continue correctly and need to know if I just always keep using this start as I keep going. The book is wonderful, but this is one point it is not really clear on.

And, I hope I am not even more confusing… LOL

Anyways, thank you.

Anyone?

I would need to go through the book again but the first look is that it looks all right.

Ok awesome. Well, now I just need help getting it to work. I just put that code together to see if I was understanding what the book is asking. However, I have not got it to work yet, so I have something wrong in there somewhere. The part from the core is just pasted directly from it. But as far is tying my part with it, I am not getting the alert to come up. What’s missing?

Once I get this working, and also undestand how it can connect to whatever I am doing, then I can continue on with the book. No point in continuing in the book if the book needs core stuff and I can’t get it to work.

So could someone please now help me get that code working? I get everything up till this point.

Am I on the right track here? And, is the point to always connect to this start code with everything I do? I ask because I am only just in the 2nd and 3rd chapters and want to continue correctly and need to know if I just always keep using this start as I keep going. The book is wonderful, but this is one point it is not really clear on.

Yeah, that sucked for me too. First I’ll go through what should be choking on what you’ve got now:


	<!-- Hide from HTML
	// code from core.js

First things first, unless you’re supporting IE5 and Nutscrape navigator, you don’t need to hide javascript from a HTML parser in a browser. So you can always lose the <!-- stuff. Not needed (also not for CSS… this is old stuff still sitting around in today’s code because of legacy browsers absolutely nobody uses anymore).


	var Core = {};
	
	Core.start = function(runnable)
	{
	  Core.addEventListener(window, "load", runnable.init);
	};
	// end of core.js

What Core does is it defines this whole function of its own called “addEventListener”, and you don’t have that. The reason it does this is mostly to combine the modern browser version of load listeners and IE’s attachEvent.
So right now you’re calling a function who’s not there
Core.addEventListener


	// Test Function
	var SayId =
	{	
		init: findId() 
		{
		var target = document.getElementById("berenger");
		alert(target.nodeName);
		}
	};
	// End of Test Function
	
	Core.start(SayId);

the init: findId() is an issue: what “init” is here is the name of a “something” in core: here, a method, because it’s a function. Any time you’re using this : syntax to define a function, you have to say so:
init: function() {
the function stuff
}

this is the same as
var init = function()
and
function = init()


What I would do for now is this:

In your <head> after all the other stuff in there:
<script type=“text/javascript” src=“core.js”></script>
<script type=“text/javascript” src=“yourscript.js”></script>

So first you call the library… a standalone file you get when you download the code archives for the book. Once you have this, it tells the browser where that file is and its javascript parser will read it.

Then it’ll read the other file, who calls it. This other file (where you are writing code you want to test, or whatever you’re copying from the book for a particular example) will be like this:



var someObject {
 // all your code
};
Core.start(someObject);

So similar to what you tried above but without the ambiguity of not having everything in the Core (which, frankly, mostly does stuff for IE, and then makes the addEventListener() function which is one way to make a script wait for page load. I believe it’s based on Simon Willison’s ideas from way back).

Though in the beginning of the book, I don’t believe he started right out with var someObject{
init: function() {your code here}
};
but introduces that later on.

You are in chapter 3? When I’m at work tomorrow I have it there and I can grab it to see what he’s got you doing there.

Well I tried this using your example and I cannot get it to work. I am so confused.

HTML


<html>
<head>
<title>Trial 2</title>
<script type="text/javascript" src="core.js"></script>
<script type="text/javascript" src="libs.js"></script>
</head>
<body>
<h1>Hello Alert</h1>				
</body>
</html>

libs.js

var someObject {
	function hello() {
	alert("Hello!");
	}
	hello();
}
Core.start(someObject);

core.js from the download

var Core = {};

// W3C DOM 2 Events model
if (document.addEventListener)
{
  Core.addEventListener = function(target, type, listener)
  {
    target.addEventListener(type, listener, false);
  };

  Core.removeEventListener = function(target, type, listener)
  {
    target.removeEventListener(type, listener, false);
  };

  Core.preventDefault = function(event)
  {
    event.preventDefault();
  };

  Core.stopPropagation = function(event)
  {
    event.stopPropagation();
  };
}
// Internet Explorer Events model
else if (document.attachEvent)
{
  Core.addEventListener = function(target, type, listener)
  {
    // prevent adding the same listener twice, since DOM 2 Events ignores
    // duplicates like this
    if (Core._findListener(target, type, listener) != -1) return;

    // listener2 calls listener as a method of target in one of two ways,
    // depending on what this version of IE supports, and passes it the global
    // event object as an argument
    var listener2 = function()
    {
      var event = window.event;

      if (Function.prototype.call)
      {
        listener.call(target, event);
      }
      else
      {
        target._currentListener = listener;
        target._currentListener(event)
        target._currentListener = null;
      }
    };

    // add listener2 using IE's attachEvent method
    target.attachEvent("on" + type, listener2);

    // create an object describing this listener so we can clean it up later
    var listenerRecord =
    {
      target: target,
      type: type,
      listener: listener,
      listener2: listener2
    };

    // get a reference to the window object containing target
    var targetDocument = target.document || target;
    var targetWindow = targetDocument.parentWindow;

    // create a unique ID for this listener
    var listenerId = "l" + Core._listenerCounter++;

    // store a record of this listener in the window object
    if (!targetWindow._allListeners) targetWindow._allListeners = {};
    targetWindow._allListeners[listenerId] = listenerRecord;

    // store this listener's ID in target
    if (!target._listeners) target._listeners = [];
    target._listeners[target._listeners.length] = listenerId;

    // set up Core._removeAllListeners to clean up all listeners on unload
    if (!targetWindow._unloadListenerAdded)
    {
      targetWindow._unloadListenerAdded = true;
      targetWindow.attachEvent("onunload", Core._removeAllListeners);
    }
  };

  Core.removeEventListener = function(target, type, listener)
  {
    // find out if the listener was actually added to target
    var listenerIndex = Core._findListener(target, type, listener);
    if (listenerIndex == -1) return;

    // get a reference to the window object containing target
    var targetDocument = target.document || target;
    var targetWindow = targetDocument.parentWindow;

    // obtain the record of the listener from the window object
    var listenerId = target._listeners[listenerIndex];
    var listenerRecord = targetWindow._allListeners[listenerId];

    // remove the listener, and remove its ID from target
    target.detachEvent("on" + type, listenerRecord.listener2);
    target._listeners.splice(listenerIndex, 1);

    // remove the record of the listener from the window object
    delete targetWindow._allListeners[listenerId];
  };

  Core.preventDefault = function(event)
  {
    event.returnValue = false;
  };

  Core.stopPropagation = function(event)
  {
    event.cancelBubble = true;
  };

  Core._findListener = function(target, type, listener)
  {
    // get the array of listener IDs added to target
    var listeners = target._listeners;
    if (!listeners) return -1;

    // get a reference to the window object containing target
    var targetDocument = target.document || target;
    var targetWindow = targetDocument.parentWindow;

    // searching backward (to speed up onunload processing), find the listener
    for (var i = listeners.length - 1; i >= 0; i--)
    {
      // get the listener's ID from target
      var listenerId = listeners[i];

      // get the record of the listener from the window object
      var listenerRecord = targetWindow._allListeners[listenerId];

      // compare type and listener with the retrieved record
      if (listenerRecord.type == type && listenerRecord.listener == listener)
      {
        return i;
      }
    }
    return -1;
  };

  Core._removeAllListeners = function()
  {
    var targetWindow = this;

    for (id in targetWindow._allListeners)
    {
      var listenerRecord = targetWindow._allListeners[id];
      listenerRecord.target.detachEvent(
          "on" + listenerRecord.type, listenerRecord.listener2);
      delete targetWindow._allListeners[id];
    }
  };

  Core._listenerCounter = 0;
}

Core.addClass = function(target, theClass)
{
  if (!Core.hasClass(target, theClass))
  {
    if (target.className == "")
    {
      target.className = theClass;
    }
    else
    {
      target.className += " " + theClass;
    }
  }
};

Core.getElementsByClass = function(theClass)
{
  var elementArray = [];

  if (typeof document.all != "undefined")
  {
    elementArray = document.all;
  }
  else
  {
    elementArray = document.getElementsByTagName("*");
  }

  var matchedArray = [];
  var pattern = new RegExp("(^| )" + theClass + "( |$)");

  for (var i = 0; i < elementArray.length; i++)
  {
    if (pattern.test(elementArray[i].className))
    {
      matchedArray[matchedArray.length] = elementArray[i];
    }
  }

  return matchedArray;
};

Core.hasClass = function(target, theClass)
{
  var pattern = new RegExp("(^| )" + theClass + "( |$)");

  if (pattern.test(target.className))
  {
    return true;
  }

  return false;
};

Core.removeClass = function(target, theClass)
{
  var pattern = new RegExp("(^| )" + theClass + "( |$)");

  target.className = target.className.replace(pattern, "$1");
  target.className = target.className.replace(/ $/, "");
};

Core.getComputedStyle = function(element, styleProperty)
{
  var computedStyle = null;

  if (typeof element.currentStyle != "undefined")
  {
    computedStyle = element.currentStyle;
  }
  else
  {
    computedStyle = document.defaultView.getComputedStyle(element, null);
  }

  return computedStyle[styleProperty];
};

Core.start = function(runnable)
{
  Core.addEventListener(window, "load", runnable.init);
};

I am so confused.

Don’t despair, this is normal : ) Stuff won’t work and it won’t work and then suddenly it works and everything makes sense… until the next thing that won’t work. I go through this every time I do something in Javascript (or Perl or whatever) and it’s normal.

Ok I’m on page 69 of my copy of the book (if you have a newer version it might be a slightly different page).

The example (which I don’t believe requires Core):


var target = document.getElementById('berenger');
alert(target.nodeName);

What I don’t see in there yet is where to put that. Before using the Core (or any other library, like jQuery which also does this), to get the above code to work (assuming you have the element with id=“berenger” of course in your HTML), you’ll put the <script> tag either after that element, or just right before the closing body tag.

So


<body>
...page blah blah
<script type="text/javascript" >
var target = document.getElementById('berenger');
alert(target.nodeName);
</script>
</body>
</html>

If you’re ever testing a trivial example like grabbing a DOM node, this will always work, in all browsers.

Test that the above style works first: this way, you know you didn’t make any typos and that there’s nothing weird in your browser setup (this is definitely important, because lots of people in the JavascriptLive had issues which were because of some other little thing instead of what they thought the problem was!). Then you can try the Core (or jQuery or whatever lib) way of doing things (below).


I believe when he introduces the whole init() stuff (page 59), he’s hoping you are remembering pages 16-17.

Now since the Core.start code looks for an inner function called init, you’ll need to change libs.js to


var someObject {
	[b]init: function()[/b] {
	    alert("Hello!");
	}
};
Core.start(someObject);

Which you can check by looking at the Robot example on page 59.


If that version all works, then something you can do for fun to test is make this change in Core:


Core.start = function(runnable)
{
  Core.addEventListener(window, "load", runnable.[b]hello[/b]);
};

and then change libs.js to this


var someObject {
	[b]hello: function()[/b] {
	    alert("Hello!");
	}
};
Core.start(someObject);

The reason (I think) why Core looks for the init() function in the object (instead of just the Object directly) is, it shouldn’t work without stating a function in the Core.start code… someObject, or Robot, or whatever aren’t functions themselves but merely Objects who contain functions. So I believe the reason Core has

Core.addEventListener(window, “load”, runnable.init);

is because you have to tell it an actual function to run (and calling the Object by itself won’t do that… the object just holds a bunch of functions together under a name). And init() throughout the book is set up in such a way that it sets up any “global” (not really, but used by the other functions) variables and sets up the event listeners, who then call all the other functions inside your Object.

And I don’t think he mentions why they do it this way, but this is a form of namespacing in Javascript, as recommended in I think chapter 10 of Javascript: the Definitive Guide by Flanagan. Meaning, your object has an init() and someone else’s also has a function named init(), but that’s ok because yours is someObject.init() (or whatever) while theirs is theirObject.init() and the JS interpreter in the browser can see those aren’t the same function despite having the same name. Same goes for variables. This keeps stuff out of the window (global) scope.

and the one thing in both of the examples that mine, nor the example of your section adding the init: part, was the = sign that would go after someObject.

Wow, I feel like a retard, I should have seen that : )

Yes, when you declare the object in that way, you’re making an assignment statement and that’s always

something = something; <–note also the semi-colon

So you can declare an object a few ways ways:
var someThing = {};
(and then
someThing.newMethod = whatever();
someThing[‘someNewProperty’] = someValue;
etc…)

or
var someThing = {
whatever: function() {
//stuff;
},
var foobar;
};

or the old way (which I’ll use for making stuff like Dates but not for plain old personal objects):

var Foo = new Object(‘whatever’);

In the whole talk about the different ways you can write a function, I thought you didn’t need one. But is that because it is an object, and because it is an object it needs the equals sign?

You need one because it’s an assignment statement.
Assignment has an = sign. Assignment is pretty much just “I’m giving a name to something.”

var foo = bar;
var someArray = [blah, blah, blah];
var someObj = {};

someDog IS-CALLED “John”. in Javascript would be
var someDog = John;

So my examples were also assignment except the first one is special (and I screwed up the last one, lawlz):

The first one is giving a name to a method (a method is a function who belongs to an Object), and when you’re naming methods like that in an Object, they are comma-separated (last one doesn’t get a comma).


var Foo [b]=[/b] {
  bar: function() {
    //do stuff;
  }[b],[/b]

  baz: function() {
    //do stuff;
  }[b],[/b]

  quux: function() {
    //do stuff;
  } <--no comma
}[b];[/b]

So those functions could also now be referred by
Foo.bar
Foo.baz
Foo.quux (dot notation)

But the other two I listed:

var init = function() {
//do stuff;
}; <–actually, looking around at code, I really can’t tell if I need one here or not. Lots of people seem to be leaving it off, so either I’m wrong or they’re relying on the nefarious “Semi-Colon Insertion” (painful-sounding and sometimes dangerous).

and this one I screwed up:
function init() { <– I had it wrong, you don’t use = here
//do stuff; <– a Do Stuff statement has no assignment but gets an ending ;
} <– no ending semi-colon

And the difference between those two ways of defining a function has to do with when they’re read: if you use the “var something = function()” version, you can’t call it earlier in the script because it hasn’t been read yet… but if you use the “function foo()” version, those functions get read (parse-time) before the script even runs, so it doesn’t matter when you call them.

Both are ways of naming a function. One uses assignment (with the = sign) and the other just states a function with a name already inside.

Since I’m confusing myself I’m probably confusing you too. So whenever you’re in doubt, just run your code through JS Lint.com (make sure you used 4 spaces for every indentation so that it actually finishes going through your script, since it will stop parsing after the gazillionth “error”… or tell it to ignore lack of 4 spaces).
Like any Lint program, it’s not a validator so much as it’s a style-checker (but it will flag actual errrors too, and really helps when dealing with semi-colons).

I will see if I can get ahold of that book… The Definitive Guide if I can also.

It’s good to have, but it’s not something you read and then can write Javascript. It’s more, Here Are The Rules According to ECMAScript. So if you want to look up how Javascript actually defines a number (if you speak C, they’re basically all double floats only), or the ways to create an Object, or whatever… it’s a good reference but it won’t tell you what WORKS the same way the W3C pages don’t tell you about browser bugs.

I have the 5th Edition and it is Good.
If you’re buying books, grab Crockford’s Javascript: the Good Parts (which is a thin small book : ) while you’re at it.

The 6th just got finished with writing and should be coming out soon. Which might nicely co-incide with IE9 supposedly supporting ECMAScript 5, which basically Mozilla has been writing (I never use the Mozilla MDC Doc Center for anything because I can never tell when what’s in there works everywhere or only in Mozilla browsers).

However, what addons for firefox to you recomend for my javascript learning process.

Firebug or Chrome developer or whatever browser debugger you like to use. I’ve only learned how to use Firebug (in a very basic way) for Javascript debugging (because of the Javascript Live course… if you have a few dollars it’s worth it to take that if you can play videos… on one of the Friday videos Kevin goes through how to debug with Firebug which was very nice for me. The course also substitutes jQuery for Core in case you were wondering how to hook up jQuery with your regular Javascript instead).
Firefox has another debugger specifically for Javascript, called Venkman (yeah, like the guy in Ghost Busters). I’ve never used it, but if you don’t like Firebug I’ve heard from others that Venkman is fantastic.

Firebug will also show you the generated HTML if you are manipulating HTML (though I’ve used the Web Developer Tool Bar for this since forever, before I knew FB does it… View Generated Source also shows you Firefox’ error-rendering mode sometimes as well). This is essential when you need to see elements you’re creating, because a regular View Source won’t show you what’s changed, but the source as the browser saw it before any manipulation.

If you’ve debugged any interpreted code before, then in Firebug once you get the script you are testing in the little console window, you can set a breakpoint, reload the page, and step through (or over, or out of) your functions, while on the right side of the console you can see your variables, scope, and some other stuff… and so even if you don’t get an actual error message, you can see why someVar isn’t updating like it should or why something isn’t happening.

What Firebug won’t tell you is why IE is puking on your JS-Lint-passing code that seems to work in all the other browsers. Now I still haven’t figured out how to use JScript debuggers in IE but it’s probably a good idea to learn one. Also there’s MSDN where Microsoft has pages listing particulars and weirdness IE does with Javascript (known internally to the browser as JScript).

Most of the basic, popular differences are web-documented (you can search for them anywhere) and any of the popular libraries (and Core) take care of the worst ones (Core fixes this, attachEvent, and a couple of others).

;-p Naw, like you mentioned earlier, it’s a language and sometimes you just forget to say something… all good. I see that with all the different ways you can choose Object or write a function, and I just have to get used to which to use when like you said.

You need one because it’s an assignment statement.
Assignment has an = sign. Assignment is pretty much just “I’m giving a name to something.”

var foo = bar;
var someArray = [blah, blah, blah];
var someObj = {};

someDog IS-CALLED “John”. in Javascript would be
var someDog = John;

So my examples were also assignment except the first one is special (and I screwed up the last one, lawlz):

The first one is giving a name to a method (a method is a function who belongs to an Object), and when you’re naming methods like that in an Object, they are comma-separated (last one doesn’t get a comma).


var Foo [b]=[/b] {
  bar: function() {
    //do stuff;
  }[b],[/b]

  baz: function() {
    //do stuff;
  }[b],[/b]

  quux: function() {
    //do stuff;
  } <--no comma
}[b];[/b]

So those functions could also now be referred by
Foo.bar
Foo.baz
Foo.quux (dot notation)

But the other two I listed:

var init = function() {
//do stuff;
}; <–actually, looking around at code, I really can’t tell if I need one here or not. Lots of people seem to be leaving it off, so either I’m wrong or they’re relying on the nefarious “Semi-Colon Insertion” (painful-sounding and sometimes dangerous).

and this one I screwed up:
function init() { <– I had it wrong, you don’t use = here
//do stuff; <– a Do Stuff statement has no assignment but gets an ending ;
} <– no ending semi-colon

Cool, I will try out these different variations to see what I get and so I get used to seeing them.

And the difference between those two ways of defining a function has to do with when they’re read: if you use the “var something = function()” version, you can’t call it earlier in the script because it hasn’t been read yet… but if you use the “function foo()” version, those functions get read (parse-time) before the script even runs, so it doesn’t matter when you call them.

Ok, now that is interesting. Should I always just use the second then?

Both are ways of naming a function. One uses assignment (with the = sign) and the other just states a function with a name already inside.

This I will just have to get used to. It seems a function and Object are almost Identical like the book mentions, just the subtle changes here or there. One uses colon and semicolon at the end… the other doesn’t.

Since I’m confusing myself I’m probably confusing you too. So whenever you’re in doubt, just run your code through JS Lint.com (make sure you used 4 spaces for every indentation so that it actually finishes going through your script, since it will stop parsing after the gazillionth “error”… or tell it to ignore lack of 4 spaces).
Like any Lint program, it’s not a validator so much as it’s a style-checker (but it will flag actual errrors too, and really helps when dealing with semi-colons).

Yes, a bit, but who cares. Anyone who enjoys teaching and helping with something is awesome. You just keep right on explaining, cause I have so many questions it’s nice to see someone with lots to say. As you see I already have my next question in the topic area… LOL.

It’s good to have, but it’s not something you read and then can write Javascript. It’s more, Here Are The Rules According to ECMAScript. So if you want to look up how Javascript actually defines a number (if you speak C, they’re basically all double floats only), or the ways to create an Object, or whatever… it’s a good reference but it won’t tell you what WORKS the same way the W3C pages don’t tell you about browser bugs.

I have the 5th Edition and it is Good.
If you’re buying books, grab Crockford’s Javascript: the Good Parts (which is a thin small book : ) while you’re at it.

The 6th just got finished with writing and should be coming out soon. Which might nicely co-incide with IE9 supposedly supporting ECMAScript 5, which basically Mozilla has been writing (I never use the Mozilla MDC Doc Center for anything because I can never tell when what’s in there works everywhere or only in Mozilla browsers).

Firebug or Chrome developer or whatever browser debugger you like to use. I’ve only learned how to use Firebug (in a very basic way) for Javascript debugging (because of the Javascript Live course… if you have a few dollars it’s worth it to take that if you can play videos… on one of the Friday videos Kevin goes through how to debug with Firebug which was very nice for me. The course also substitutes jQuery for Core in case you were wondering how to hook up jQuery with your regular Javascript instead).
Firefox has another debugger specifically for Javascript, called Venkman (yeah, like the guy in Ghost Busters). I’ve never used it, but if you don’t like Firebug I’ve heard from others that Venkman is fantastic.

Firebug will also show you the generated HTML if you are manipulating HTML (though I’ve used the Web Developer Tool Bar for this since forever, before I knew FB does it… View Generated Source also shows you Firefox’ error-rendering mode sometimes as well). This is essential when you need to see elements you’re creating, because a regular View Source won’t show you what’s changed, but the source as the browser saw it before any manipulation.

If you’ve debugged any interpreted code before, then in Firebug once you get the script you are testing in the little console window, you can set a breakpoint, reload the page, and step through (or over, or out of) your functions, while on the right side of the console you can see your variables, scope, and some other stuff… and so even if you don’t get an actual error message, you can see why someVar isn’t updating like it should or why something isn’t happening.

What Firebug won’t tell you is why IE is puking on your JS-Lint-passing code that seems to work in all the other browsers. Now I still haven’t figured out how to use JScript debuggers in IE but it’s probably a good idea to learn one. Also there’s MSDN where Microsoft has pages listing particulars and weirdness IE does with Javascript (known internally to the browser as JScript).

Most of the basic, popular differences are web-documented (you can search for them anywhere) and any of the popular libraries (and Core) take care of the worst ones (Core fixes this, attachEvent, and a couple of others).

Awesome, I will check some of this stuff out and see what happens. Cool stuff.

Thanks, and when you get a chance, see what you think about my other question topic. Again, when you have time. again, thanks so much.

J.

Ok, now that is interesting. Should I always just use the second then?

For some reason I tend to use var foo = function() but if you’re worried about not being careful you can use the other form.

Or, do what people in other programming languages do: declare the functions near the top of your script, or at least before you call them. If you’re using the second form then Javascript is pretty cool that you can declare all your functions at the bottom or the middle or whereever and it doesn’t matter when you call them.

This I will just have to get used to. It seems a function and Object are almost Identical like the book mentions, just the subtle changes here or there. One uses colon and semicolon at the end… the other doesn’t.

I found getting the syntax straight (and it’s still not always straight in my head) was a hurdle.

But so you know, everything in Javascript is an object. Functions are objects. Arrays are objects. Really everything except simple variables are objects.