Giới thiệu về ngữ pháp
// The "console.log" in the text can be replaced by the Log function in the debugging of FMZ
// The way of remarks is similar to C; this is a single line remark
/* These are multi-line
remarks */
// Statements can end with a semicolon
doStuff();
// ... But the semicolon can also be omitted, whenever a new line is encountered, the semicolon is automatically inserted (except for some special cases)
doStuff()
// Because those special cases can cause unexpected results, we preserve the semicolon here
///////////////////////////////////
// 1. Number, String and Operator
// Javascript only has one number type (namely 64-bit IEEE 754 double)
// double has 52 bits for fraction, precise enough to store integers as big as 9✕10¹⁵
3; // = 3
1.5; // = 1.5
// All basic arithmetic operations work as you would expect
1 + 1; // = 2
0.1 + 0.2; // = 0.30000000000000004
8 - 1; // = 7
10 * 2; // = 20
35 / 5; // = 7
// Including division methods that are not evenly divisible
5 / 2; // = 2.5
// The bit operation is also same as that of other languages; when you do bit operation to the float
// the float will convert into an unsigned integer *no more than* 32 bits
1 << 2; // = 4
// The grouping operator can control the precedence
(1 + 3) * 2; // = 8
// There are three number types in non-numeric form
Infinity; // the result of 1/0
-Infinity; // the result of -1/0
NaN; // the result of 0/0
// There is also boolean value
true;
false;
// You can create strings by single or double quotation marks
'abc';
"Hello, world";
// Use operator ! to perform "logical NOT" operation
!true; // = false
!false; // = true
// Strict equality ===
1 === 1; // = true
2 === 1; // = false
// Inequality !=
1 !== 1; // = false
2 !== 1; // = true
// More comparison operators
1 < 10; // = true
1 > 10; // = false
2 <= 2; // = true
2 >= 2; // = true
// Use + to connect strings
"Hello " + "world!"; // = "Hello world!"
// You can also use < 、> to compare strings
"a" < "b"; // = true
// When using == to compare, the type will be converted
"5" == 5; // = true
null == undefined; // = true
// ... except that you use ===
"5" === 5; // = false
null === undefined; // = false
// ... but that will result in a strange action
13 + !0; // 14
"13" + !0; // '13true'
// You can use `charAt` to get the character in a string
"This is a string".charAt(0); // = 'T'
// ... or you can use `substring` to obtain a bigger part
"Hello world".substring(0, 5); // = "Hello"
// `length` is a property, so do not use ().
"Hello".length; // = 5
// There are also two special values: `null` and `undefined`
null; // To express the deliberately set null
undefined; // To express the value not set yet (although `undefined` itself is actually a value)
// false, null, undefined, NaN, 0 and "" are all false; others are regarded as logically true
// Pay attention that 0 is logically false, while "0" is logically true, although 0 == "0"
///////////////////////////////////
// 2. Variable, Array and Object
// A variable needs to use the keyword `var` to make a declaration. Javascript is a dynamic programming language,
// so you do not need to specify types and you assign with `=`
var someVar = 5;
// If you did not add `var` in the declaration, you will not get an error, either...
someOtherVar = 10;
// ... but the variable will be created in the global scope, not in the current scope defined by you
// All variables without assignment will be set as undefined
var someThirdVar; // = undefined
// some abbreviated syntaxes for the math operations of variables:
someVar += 5; // equal to someVar = someVar + 5; someVar now is 10
someVar *= 10; // now someVar is 100
// There are also abbreviations for auto-increment and auto-decrement
someVar++; // someVar means 101
someVar--; // return to 100
// An array is an ordered list composed of any types
var myArray = ["Hello", 45, true];
// The elements of an array can be accessed by the square brackets []
// The index of an array starts from 0
myArray[1]; // = 45
// An array is variable, with an variable length
myArray.push("World");
myArray.length; // = 4
// Add or modify at the specified subscripts
myArray[3] = "Hello";
// An object in javascript equals "dictionary" or "map" in other languages: it is a disordered collection of the key-value pair
var myObj = {key1: "Hello", key2: "World"};
// Key is a string, but if the key itself is not a legal js identifier, the quotation mark is not necessary
// The value could be any type
var myObj = {myKey: "myValue", "my other key": 4};
// The object property can be accessed by subscripts
myObj["my other key"]; // = 4
// ... or by '.', if the property is a legal identifier
myObj.myKey; // = "myValue"
// The object is variable; the value can also be modified or added with a new key
myObj.myThirdKey = true;
// If you want to obtain an undefined value, then return undefined
myObj.myFourthKey; // = undefined
///////////////////////////////////
// 3. Logic and Control Structure
// The syntax introduced in this section is almost the same as that of Java
// Statement `if` is the same as other languages
var count = 1;
if (count == 3){
// Execute when count is 3
} else if (count == 4){
// Execute when count is 4
} else {
// Execute in other cases
}
// while loop
while (true) {
// infinite loop
}
// Do-while loop and While loop are similar, but the former at least will be executed once
var input;
do {
input = getInput();
} while (!isValid(input))
// `for`loop is the same as that in C and Java:
// Initialize; conditions for continuous execution; iteration
for (var i = 0; i < 5; i++){
// Traverse 5 times
}
// && is logical AND; || is logical OR
if (house.size == "big" && house.colour == "blue"){
house.contains = "bear";
}
if (colour == "red" || colour == "blue"){
// Execute when colour is red or blue
}
// && and || are short circuit statements,which are very useful when setting initialization
var name = otherName || "default";
// `switch` uses `===` to detect the equality
// When each case is over, use 'break'
// Or the case statement after the former will be executed
grade = 'B';
switch (grade) {
case 'A':
console.log("Great job");
break;
case 'B':
console.log("OK job");
break;
case 'C':
console.log("You can do better");
break;
default:
console.log("Oy vey");
break;
}
///////////////////////////////////
// 4. Function, Scope and Closure
// Function in JavaScript is defined by `function`
function myFunction(thing){
return thing.toUpperCase();
}
myFunction("foo"); // = "FOO"
// Pay attention that the returned value has to start from the line of `return`
// Or return `undefined`, due to the auto-completion of semicolon
// Pay attention when you use Allman style
function myFunction()
{
return // <- semicolon will automatically insert here
{
thisIsAn: 'object literal'
}
}
myFunction(); // = undefined
// Function in javascript is first class object, so function can be assigned to a variable
// Also can be passed as parameter - such as a function processing an event:
function myFunction(){
// This piece of code will be called after 5 seconds
}
setTimeout(myFunction, 5000);
// Note: setTimeout is not a part of js language; it is provided by the browser and Node.js
// The function object does not even need to declare its name - you can directly write the definition of one function into the parameters of another function
setTimeout(function(){
// This piece of code will be called after 5 seconds
}, 5000);
// JavaScript has function scope; functions have their own scope and other codes do not have that
if (true){
var i = 5;
}
i; // = 5 - not the undefined that we expect to get in other languages
// That leads to theh mode of "immediately-invoked function expression" commonly used by people
// Which can avoid some temporary variables spreading into the global scope
(function(){
var temporary = 5;
// We can access and modify the global object to access the global scope
// In web browser, it is the object `window`
// In other environments, such as Node.js, the name of the object can be different
window.permanent = 10;
})();
temporary; // Raise ReferenceError
permanent; // = 10
// One of the most powerful functions of javascript is closure
// If define one function in another function, then the inner function has the access privilege of all variables in the outer function
// Even after the outer function is finished
function sayHelloInFiveSeconds(name){
var prompt = "Hello, " + name + "!";
// The inner function is, by default, put in the local scope
// Just like declared by `var`
function inner(){
alert(prompt);
}
setTimeout(inner, 5000);
// setTimeout is async, so sayHelloInFiveSeconds function will exit immediately
// While setTimeout will call inner after that
// However, for inner is "contained in form of closure" by sayHelloInFiveSeconds
// inner can still access the variable `prompt`, when it is called in the final
}
sayHelloInFiveSeconds("Adam"); // "Hello, Adam!" will prompt after 5 seconds
///////////////////////////////////
// 5. Object, Constructor and Prototype
// Object can contains methods
var myObj = {
myFunc: function(){
return "Hello world!";
}
};
myObj.myFunc(); // = "Hello world!"
// When a function in the object is called, the function can access the object it depends on by `this`
myObj = {
myString: "Hello world!",
myFunc: function(){
return this.myString;
}
};
myObj.myFunc(); // = "Hello world!"
// But the environment the function accesses is actually its running environment, not the defined environment, that is, it really depends on how the function is called
// So if the function is not in the context of the object when it is called, the operation of the function will fail
var myFunc = myObj.myFunc;
myFunc(); // = undefined
// Correspondingly, a function can be specified as a method of an object, and be accessed by `this`
// The member of the object, even if the function did not depend on the object when it is defined
var myOtherFunc = function(){
return this.myString.toUpperCase();
}
myObj.myOtherFunc = myOtherFunc;
myObj.myOtherFunc(); // = "HELLO WORLD!"
// When we call a function by `call` or `apply`, we can also specify an execution context for it
var anotherFunc = function(s){
return this.myString + s;
}
anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"
// `apply` function is almost the same, and only one array in request to pass the parameter list
anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!"
// When a function receives a series of parameters, it is very useful if you want to pass an array
Math.min(42, 6, 27); // = 6
Math.min([42, 6, 27]); // = NaN (uh-oh!)
Math.min.apply(Math, [42, 6, 27]); // = 6
// But `call` and `apply` are just temporary. If we want the function to depend on the object, use `bind`
var boundFunc = anotherFunc.bind(myObj);
boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!"
// `bind` can also be used to partially apply a function (currying)
var product = function(a, b){ return a * b; }
var doubler = product.bind(this, 2);
doubler(8); // = 16
// When you call a function by `new`, an object will be created
// And you can access the function by `this`
// The function designed to be invoked like this is constructor
var MyConstructor = function(){
this.myNumber = 5;
}
myNewObj = new MyConstructor(); // = {myNumber: 5}
myNewObj.myNumber; // = 5
Đọc thêm
JavaScript: Hướng dẫn cuối cùnglà một tài liệu tham khảo hướng dẫn cổ điển.