Monday, 30 December 2013

Head First HTML5 - JavaScript notes (2)

"namespace"


  • There is no strict "namespace" construct in JavaScript similar to C#. The notion of "namespace" is used to reduce the scope of the variables and prevent polluting the global namespace. 

The output looks like the following:
Simple "Namespace" 

  • The next step is to add functions to this namespace. We can use a self-executing function for this purpose. See the following. The idea is to add our custom functions to the namespace.



Saturday, 28 December 2013

Head First HTML5 - JavaScript notes (1)


Basic
  • JavaScript is not a statically typed language. The core types are Object, String, Number, Boolean.
  • The properties of an object can be accessed through "." or ["property name"] syntax (e.g. obj["name"], obj.name)
  • Arrays are pretty standard. Two ways of declaring. See below:
  • JavaScript objects are not "typed", instead think in terms of the "shape" of the object. See below.



Functions
  • Functions does not require a name. This is like anonymous functions in C#.
  • Functions can be considered "value" and it can be passed around as variable. Think about "Action" or "Func" (delegates) in C#.
  • Variables declared as "var" in functions scoped to the function itself. It is a good practice to scope variables to functions. 
  • Normally when passing arguments to functions, be aware that the primitive types are passed by "value" and objects are passed by "reference". The "reference" allows to get to the original object, similar to C#. See the following code.


  • Objects can contain behaviour which is achieved through functions (method). See below: 
  



  • The notion of constructor can be used to create an "object". The constructor in this case is a function.  See the following:




Most importantly the "new" keyword is used to create a new instance of "Dog". Its a convention to capitalise the constructor function.

  • The methods attached to an object can use "this" in the body. The "this" keyword refers to the object that the method is contained in. Normal functions may not use "this" in the similar fashion to a method in an object.