Dave's Javascript Blog
Monday, April 6, 2015
Google Tag Manager Experiment
This is an experiment to use Google Tag Manager to display a alert when ever this page is rendered.
Saturday, September 20, 2014
Javascript - Ajax and Json
What's web service?
A web service is a file or program that can provide data to your web application.
What's Json?
JSON is short for Javascript Object Notation. It's a data exchange format. Another popular data exchange format is XML. JSON and XML are both capable of representing your application data. Whether to use JSON or XML depends on the type of the data, the web application or the program or web services with which you are exchanging your data with. Typically, JSON is used mostly in web applications.
Why Json?
- Its format is almost identical to the way you write arrays and objects in javascript, thus more human readable and easier to parse than XML.
- Can be used to convert objects into string, and then store them in a file or send them to web applications/services that are written in different programming languages.
What's Ajax?
The main goal behind Ajax is to make web pages behaves like a desktop application. Ajax represents a collection of techniques. In a nutshell, it consists of the following steps.
The most important feature of Ajax is it enables the page to send and receive data from the server without causing the page to hang or reload. As mentioned before, the goal of Ajax is to make web pages behave like a desktop application. The flow of user interaction is the most important and should not be interrupted by page hanging or reloading. Ajax solves this problem.
- Requests data from server
- Stays on the current page and waits for the response while still be able to interact with user
- Receives data from the server and updates only parts of the page.
The most important feature of Ajax is it enables the page to send and receive data from the server without causing the page to hang or reload. As mentioned before, the goal of Ajax is to make web pages behave like a desktop application. The flow of user interaction is the most important and should not be interrupted by page hanging or reloading. Ajax solves this problem.
What's Cross-Domain Security Restriction?
Tuesday, July 22, 2014
Javascript Learning Note - The very Basics
First of all, Javascript is an object-based language, it has a lot features that're similar to those of Object-Oriented language, but they are not exactly the same.
You can put your javascript code anywhere in your HTML file, whether its in the head, body or after body. One thing worth noting is that the browser will evaluate and run your code top-down, so the order of your javascript code matters as those ones on the top is executed before those ones at the bottom.
You can write javascript code within the script tag directly or use the src attribute to link to an external javascript file. The convention is if the javascript code is only used within that html, then put the code in there, otherwise create a javascript file and set a link to it.
var x = 3+1;
is a statement
the 3+1 is an expression.
An event is something that happens in your JavaScript program that you can choose to handle. Events can be generated by you (like if you click a mouse), or generated by the browser (like if the page has completed loading), or even generated by JavaScript itself (like if a timer goes off).
What's event handler?
The value of the aGlobalVariable is not changed, because parameters are local variables. Inside the function tryToChangeGlobalVariable, aGlobalVariable is actually a local variable, it gets the value from the global variable with the same name, but it would not effect the value of the global variable.
TypeError: Cannot set property 'backgroundColor' of undefined
That's because the first child within the div main is not the p tag object. Then what is the first child of the div main? The answer is text node. Look at the whites spaces and new line before the the end tag of div and the start tag of p. They are stored as text node within DOM. These text nodes are just like element objects, but they don't have some of the properties element objects have. You need to avoid getting the text node when you are actually trying to get an element node.
You can put your javascript code anywhere in your HTML file, whether its in the head, body or after body. One thing worth noting is that the browser will evaluate and run your code top-down, so the order of your javascript code matters as those ones on the top is executed before those ones at the bottom.
<html lang="en"> <head> <title> My First JavaScript </title> <script> //Javascript code here </script> </head> <body> <script> //Javascript code here </script> </body> <script> //Javascript code here </script> </html>
You can write javascript code within the script tag directly or use the src attribute to link to an external javascript file. The convention is if the javascript code is only used within that html, then put the code in there, otherwise create a javascript file and set a link to it.
Statements and expression
Each line in javascript code is a statement. Expression is the part of a statement that has value. For example,var x = 3+1;
is a statement
the 3+1 is an expression.
Document Object Model
document is a built-in javascript object that gives you access to the elements in your page through javascript code.
The default object of any javascript program is window, alert, console and document all belong to the window object. Try putting window before them, the result is the same.
The default object of any javascript program is window, alert, console and document all belong to the window object. Try putting window before them, the result is the same.
window.alert("Hello"); window.console.log("Hi"); window.document.getElementById("someId");
Functions and Events
What's events?An event is something that happens in your JavaScript program that you can choose to handle. Events can be generated by you (like if you click a mouse), or generated by the browser (like if the page has completed loading), or even generated by JavaScript itself (like if a timer goes off).
What's event handler?
Event handler are just function that are assigned to an event.
Javascript functions are pass by value.
Scope
Global variables are declared outside functions, they have global scope.
Local variables are declared within functions, they have local scope.
Functions parameters have local scope. Take a look at the following code snippet.
test.js
test.js
var aGlobalVariable = 3; console.log("Global variable before calling the function: "+aGlobalVariable); tryToChangeGlobalVariable(aGlobalVariable); console.log("Global variable after calling the function: "+aGlobalVariable); function tryToChangeGlobalVariable(aGlobalVariable){ aGlobalVariable = 5; }
The output are
Global variable before calling the function: 3 Global variable before calling the function: 3
The value of the aGlobalVariable is not changed, because parameters are local variables. Inside the function tryToChangeGlobalVariable, aGlobalVariable is actually a local variable, it gets the value from the global variable with the same name, but it would not effect the value of the global variable.
Node and Text Node
Objects in DOM are sometimes referred to as nodes. There are two kinds of node, element node which are equivalent to element object, and text node. Text node are very different from element node as it does not have the properties element node contains. Take a look at the following code snippet.
If you run this code, you will get an typeError<html lang="en"> <head> <title> My First JavaScript </title> <script> window.onload = init; function init(){ var firstNode = document.getElementById("main").firstChild; firstNode.style.backgroundColor = "blue"; } </script> </head> <body> <div id="main"> <p>This is not the first child node of div main</p> </div> </body> </html>
TypeError: Cannot set property 'backgroundColor' of undefined
That's because the first child within the div main is not the p tag object. Then what is the first child of the div main? The answer is text node. Look at the whites spaces and new line before the the end tag of div and the start tag of p. They are stored as text node within DOM. These text nodes are just like element objects, but they don't have some of the properties element objects have. You need to avoid getting the text node when you are actually trying to get an element node.
Methods & Properties Used to Manipulate DOM
Properties
childNodes - store all the child nodes
firstChild - store the first child node
parentNode - store the parent node
Methods
appendChild() - append a node
removeChild() - remove a node
querySelector() - return the first element object specified in the argument, the argument is very similar to how css locate the object in DOM
querySelectorAll() - return all the element objects that match the argument
childNodes - store all the child nodes
firstChild - store the first child node
parentNode - store the parent node
Methods
appendChild() - append a node
removeChild() - remove a node
querySelector() - return the first element object specified in the argument, the argument is very similar to how css locate the object in DOM
querySelectorAll() - return all the element objects that match the argument
Tuesday, February 4, 2014
Javascript Types
We can categorize Javascript data types in different ways.
Category I
- Primitive Types
- Object Types
Category II
- Have Methods
- Don't Have Methods
Category III
- Immutable
- Mutable
Monday, December 2, 2013
Function Invocation
Javascript functions can be invoked in four ways:
functions,
methods,
constructors,
call() and apply()
They differs from each other in various ways, and most importantly in invocation context and returning mechanisms.
First of all, let's introduce a definition called invocation expression. An invocation expression consists of a function expression that evaluates to a function object followed by an open parenthesis, a comma-separated list of zero or more argument expressions, and a close parenthesis.
Now let's dive into each type of function invocation one by one. The first one is called Function Invocation. When a function is invoked as function, it's invoked using invocation expression. The line
sum(1, 1); in the example below is a function invocation. It has the function expression sum, an open and close parenthesis and argument expressions 1, 1.
Method invocation is similar. It's just a function stored in a property of an object. Specify the object on which this method is called before the invocation expression when you invoke a method. See the example below. calculator is the name of the object and add() is the invocation expression. Any function that is used as method is effectively passed an implicit argument - the object through which it is invoked.
If a function or method invocation is preceded by the keyword new, then it is a constructor invocation. A constructor invocation creates a new, empty object that inherits from the prototype property of the constructor.
Javascript functions are also objects. It has its own methods. Two of them are called apply and call, which can be used to invoke the function indirect, and by using them, you can also specify the invocation context as the first argument. See example below.
Invocation Context for different types of function invocation.
functions,
methods,
constructors,
call() and apply()
They differs from each other in various ways, and most importantly in invocation context and returning mechanisms.
First of all, let's introduce a definition called invocation expression. An invocation expression consists of a function expression that evaluates to a function object followed by an open parenthesis, a comma-separated list of zero or more argument expressions, and a close parenthesis.
Now let's dive into each type of function invocation one by one. The first one is called Function Invocation. When a function is invoked as function, it's invoked using invocation expression. The line
sum(1, 1); in the example below is a function invocation. It has the function expression sum, an open and close parenthesis and argument expressions 1, 1.
function sum(x, y){ console.log('The sum of x and y is '+ (x+y)) } sum(1, 1);
Method invocation is similar. It's just a function stored in a property of an object. Specify the object on which this method is called before the invocation expression when you invoke a method. See the example below. calculator is the name of the object and add() is the invocation expression. Any function that is used as method is effectively passed an implicit argument - the object through which it is invoked.
var calculator = { operator1: 1, operator2: 1, add: function(){ console.log('The sum is '+(this.operator1+this.operator2)); } } calculator.add();
If a function or method invocation is preceded by the keyword new, then it is a constructor invocation. A constructor invocation creates a new, empty object that inherits from the prototype property of the constructor.
var arr = new Array(); //By convention, constructors start with capitals
Javascript functions are also objects. It has its own methods. Two of them are called apply and call, which can be used to invoke the function indirect, and by using them, you can also specify the invocation context as the first argument. See example below.
function sum(x, y){ console.log('The sum of x and y is '+ (x+y)) } sum.call(undefined, 1, 1); sum.apply(null, [1, 1]);
Invocation Context for different types of function invocation.
Non Strict Mode | Strict Mode | |
Function Invocation | global | undefined |
Method Invocation | the caller object | the caller object |
Constructor Invocation | the new object | the new object |
Indirect Invocation | can be specified | can be specified |
Sunday, December 1, 2013
Javascript - Why Assign this value in self
In Javascript, we see this line of code frequently
self = this;
We know this refers to the invocation context, but why we need to assign its value to a variable. The reason is this keyword does not have a scope, and nested functions do not inherit the this value of their caller. Thus if a nested function is invoked as a function, its this keyword actually refers to global object (non-strict mode) or undefined (strict mode). In order to access the invocation context of the outer function, we need to assign the value of this keyword to a variable. Recalling from our previous blog Variable Scope & Function Scope, we have variables are visible within the function in which they are defined and within any functions that are nested within that function. Now let's take a look at the following code snippet.
self = this;
We know this refers to the invocation context, but why we need to assign its value to a variable. The reason is this keyword does not have a scope, and nested functions do not inherit the this value of their caller. Thus if a nested function is invoked as a function, its this keyword actually refers to global object (non-strict mode) or undefined (strict mode). In order to access the invocation context of the outer function, we need to assign the value of this keyword to a variable. Recalling from our previous blog Variable Scope & Function Scope, we have variables are visible within the function in which they are defined and within any functions that are nested within that function. Now let's take a look at the following code snippet.
var o = { m: function(){ var self = this; console.log(this===o); // return true f(); //invoking nested function as a function //nested function function f(){ console.log(this===o); // return false console.log(self===o); // return true } } } o.m();
Tuesday, November 26, 2013
Variable Scope & Function Scope
According to the book Javascript The Definitive Guide, The scope of a variable is the region of your program source code in which it is defined. A global variable has global scope; it is defined everywhere in your Javascript code. On the other hand, variables declared within a function are defined only within the body of the function. Open up your javascript interactive console and let's do some experiments.
As we can see here, we can access global variable outside the function body but not local variable, because it is only accessible within the body of the function.
From the example above, we can actually see another feature of javascript, called Function scope: variables are visible within the function in which they are defined and within any functions that are nested within that function.
Compare the two code snippet of Java and Javascript.
Compile and run this Java code and you'll get the following error. That's because Java has block scope, which means each block of code within curly braces has its own scope, and variables are not visible outside of the block in which they are declared.
However, the following javascript code will run successfully all because Javascript is a function-scope language.
js> var a_global_var = 'global'; js> function local_scope_demo(){ var a_local_var = 'local'; } js> a_global_var "global" js> a_local_var typein:25: ReferenceError: a_local_var is not defined
As we can see here, we can access global variable outside the function body but not local variable, because it is only accessible within the body of the function.
From the example above, we can actually see another feature of javascript, called Function scope: variables are visible within the function in which they are defined and within any functions that are nested within that function.
Compare the two code snippet of Java and Javascript.
public class HelloWorld { public static void main(String[] args) { for(int i=0;i<10;i++){ System.out.println("i in the for loop is "+i); } System.out.println("i out of for loop is "+i); } }
Compile and run this Java code and you'll get the following error. That's because Java has block scope, which means each block of code within curly braces has its own scope, and variables are not visible outside of the block in which they are declared.
cannot find symbol symbol : variable i location: class HelloWorld System.out.println("i out of for loop is "+i); ^ 1 error
However, the following javascript code will run successfully all because Javascript is a function-scope language.
function function_scope_demo(){ for(var i=0;i<10;i++){ console.log(k); } console.log(k); // k is 10 }
Subscribe to:
Posts (Atom)