3. JavaScript (JS)
Created in 1995 by Brendan Eich
Name: Mocha in LAB, LiveScript for Netscape Navigator 2.0 and last rename to
JavaScript with Netscape 2 beta in December 1995
Microsoft add JavaScript to IE in 1996 called JScript
6. Stuff You Should Know
JavaScript run in Web Browser
JavaScript integrate with DOM
JavaScript is a dynamic type
Current JavaScript complied to ECMA-262 version 5.1
http://en.wikipedia.org/wiki/ECMAScript
JavaScript no coding standard, has only Best Practice
10. JavaScript Basic Programming
Declare Variable
var testString = 'ASP.NET & MVC Developers Thailand';
var testInt = 2000;
var testBool = true;
var testDouble = 2000.2334;
var testReg = /(?:.d){2}/;
var testUndefined;
var testNull = null;
var testArray = new [0, 1, 2, 3];
var testObj = new {};
var testFunc = new function () { };
11. JavaScript Basic Programming
Declare Function
//Declare function
function MVCShowOff() { return "Hi there, we are X!!"; }
var message = MVCShowOff(); //call
//Declare varriable function
var MvcShowOff = function () { return "Hi there, we are X!!"; };
message = MvcShowOff(); //call
//Declare Self-Invoking function
(function () { return "Hi there, we are X!!"; })();//<-- (); is a caller
//Declare Annonymous Function
document.onload = function (e) { alert("Hi there, we are X!!"); };
12. JavaScript Basic Programming
Parameter Function
//Declare Function with parameter
function Mid2Vals(hi, low) { return (hi + low) / 2; }
var result = Mid2Vals(5, 10);
//Declare Function without parameter and use arguments parameter
function Mid2Vals() { return (arguments[0] + arguments[1]) / 2; }
var result = Mid2Vals(5, 10);
13. JavaScript Basic Programming
Class and Object
//1. Declare Object Type, Class
function MvcMember() {
this.name = "Nine not K9";
this.isInstuctor = true;
};
//Declare varriable and call
var mrNine = new MvcMember();
alert(mrNine.isInstuctor); // true
//2. Declare Object literal
var mrNine = {
name : "Nine not K9",
isInstuctor : true
};
//Call
alert(mrNine.isInstuctor); // true
14. JavaScript Basic Programming
Complex Class Object
//1. Declare Class
function MvcMember() {
this.name = "Nine not K9";
this.isInstuctor = true;
this.event = new function Event() {
this.name = "Zubzib Black Coffee #5 Update Skills v1";
this.session = new function Session() {
this.name = "JavaScript for Web Developer";
this.audiences = 40; };
this.place = "University of Thai Chamber of Commerce";
this.location = new function Location() {
this.lat = 13.779276;
this.long = 100.560326;
this.getGeoLocation = lat + ', ' + long; };};};
//2. Initial varriable and access data
var mrNine = new MvcMember();
alert(mrNine.event.name);
alert(mrNine.event.session.name);
alert(mrNine.event.location.getGeoLocation);
15. JavaScript Basic Programming
Late Declare Variable and Function
//1. Declare Class
function MvcMember() {
this.name = "Nine not K9";
this.isInstuctor = true;
};
//And initial an object
var mrNine = new MvcMember();
//2. late declare variable
mrNine.say = "Hi everybody"; // mrNine["say"] = "Hi everybody"; //same
//3. late declare function
mrNine.thinkAbout = function (source) { return "I'm thinking about the " + source; };
16. JavaScript Basic Programming
Condition, Loop, try… catch
//IF Else condition
var x = 0, y = 1;
if (x == 1) { alert('Yes'); }
else { alert('No'); }
//Switch Condition
var word = "Hi";
switch (word) {
case "Hi":
alert('How r u?');
default:
alert("Hey what's was wrong with you?");
}
//While loop
var x = 5;
while (x<1) { x--; }
alert(x);
//For loop
var title = "JavaScript".split('');
for (var i = 0; i < title.length; i++) {
alert(title[i]);
}
17. JavaScript Basic Programming
Condition, Loop, try… catch
// For Each Loop
var topic = "JavaScript very easy".split(' ');
topic.forEach(function(word) { alert(word); });
//try catch block
try {
var x;
x.ErrorPlease();
} catch(e) {
alert("catch error : " + e.message);
}
18. JavaScript Basic Programming
Comparisons 1
// Assigh value
var x = 10;
console.log("x="+x);
//Comparison
var a = "test", b = "TEST";
var result = a == b;
console.log("comparison a == b ? "+result);
//Identity
var identityResult = a === x;
console.log("identity a is b ? " + identityResult);
19. JavaScript Basic Programming
Comparison 2
//check base type and value type
var undef;
var num = 90;
var str = "Test";
var bool = true;
var func = function (a, b) { return a + b; };
var object = { x: 500 };
var arr = ["Nine", "Non", "Tape"];
console.log(typeof undef); //"undefined"
console.log(typeof num); //"number"
console.log(typeof str); //"string"
console.log(typeof bool); //"boolean"
console.log(typeof func); //"function"
console.log(typeof object); // "object"
console.log(typeof arr); // "object"
//check object instance of class
var arr = ["Nine", "Non", "Tape"];
console.log(arr instanceof Array); // true
function Speaker() { this.name = "Nine"; }
var mrNine = new Speaker();
console.log(mrNine instanceof Speaker); // true
20. JavaScript Basic Programming
Value of variables are always false in condition
var a = null;
var b; // undefined
var c = 0;
var d = false;
var e = "";
if (a) // false
if (b) // false
if (c) // false
if (d) // false
if (e) // false
21. JavaScript Basic Programming
Inheritance with Prototype
function Speaker(isSpeaking) { this.isSpeaking = isSpeaking == null ? false :
isSpeaking; }
Speaker.prototype.say = function () {return "Break session"; };
function ZZSpeaker () { this.isEating = true; }
ZZSpeaker.prototype = new Speaker();
ZZSpeaker.prototype.sleepyShow = function () { alert('wake up !!!'); };
ZZSpeaker.prototype.say = function () { return "Ask me please.."; };
var nineSpeak = new ZZSpeaker();
nineSpeak.say();
nineSpeak.sleepyShow();
22. 3rd JavaScript Framework and
Library
jQuery is a library created on top JavaScript, to help us access DOM and populate HTML
element, content , CSS, animation and DOM Event
The two thinks jQuery dose
1. SELECT elements or a group of element by CSS Selector
2. Take Action on elements
23. 3rd JavaScript Framework and
Library
jQuery : Get Started
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="test"></div>
<!-- 1. Add script reference to local or CDN -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
//2. declare document ready
$(document).ready(function () {
$('div.test').html("<h1>JavaScript for web developer</h1>");
});
</script>
</body>
</html>
24. 3rd JavaScript Framework and
Library
jQuery : query and action
<div class="test"></div>
<input id="btnShowMessage" type="button" value="click me" />
//2. declare document ready
$(document).ready(function () {
//3. Bind Element Action to custom function
$('#btnShowMessage').click(function () {
$('div.test').html("<h1>DOM Ready binding event</h1>");
});
});
//4. Early binding event can declare out of DOM Ready block
$('#btnShowMessage').on('click', function () {
$('div.test').html("<h1>Early binding event</h1>");
});
29. Use AJAX (native code)
// This is the client-side script
// Initialize the Ajax request
var xhr = XMLHttpRequest();
xhr.open('get', 'http://google.com');
// Track the state changes of the request
xhr.onreadystatechange = function () {
// Ready state 4 means the request is done
if (xhr.readyState === 4) {
// 200 is a successful return
if (xhr.status === 200) {
alert(xhr.responseText); // 'This is the returned text.'
} else {
alert('Error: ' + xhr.status); // An error occurred during the request
} }}
// Send the request to send-ajax-data.php
xhr.send(null);
30. Use AJAX with JQUERY
$.get()
$.post()
$.getJSON()
$.ajax()
Demo
$.get('ajax/test.html', function (data) {
$('.result').html(data);
alert('Load was performed.');
});
$.post('ajax/test.html', function (data) {
$('.result').html(data);
});
$.getJSON('ajax/test.json', function (data) {
var items = [];
$.each(data, function (key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
});
33. JSON : JavaScript Object Notation
JSON is a text-based open standard designed for human-readable data interchange
//JavaScript Object
var session = { name: 'Nine', sessionName: 'JavaScript for Web Developer', };
//JSON Object
{"name": "Nine", "sessionName" : "JavaScript for Web Developer" }
34. JSON
JavaScript Object to JSON
var session = { name: $('input#name').val(), sessionName:
$('input#sesseionName').val() };
//convert to json
var json = JSON.stringify(session);