Before reading this book, I would like to thank the Taobao technical team for the translation of this JavaScript core and Flanagan for writing this book. Thank you for your selfless sharing, and only this note is dedicated to your hard work.
1: JavaScript Language Core
After this chapter, we will focus mainly on the basics of javascript. Chapter 2 We will explain the comments, semicolons and unicode character sets of javascript; Chapter 3 will be more interesting, mainly explaining the variables and assignments of javascript
Here are some example codes to illustrate the key contents of the first two chapters.
The code copy is as follows:
<script type="text/javascript">
//The content after the double slash belongs to the comment
//Read the comments here carefully, it will explain the javascript code
// Variable is a symbolic name that represents the value
// Variables are declared via the var keyword
var x; //Declare a variable x
//The value can be assigned to the variable through symbols
x = 0; //The value of variable x is now 0
x //Get its value by variable name.
//javascript supports multiple data types
x = 1; //Number
x = 0.01; //Integers and real numbers share a data type
x = "hello world"; //Construct a string of text in double quotes
x = 'hello world'; //Single quotes also form strings.
x = true; //Boolean
x = false; // Another boolean value
x = null; //null is a special value. Meaning empty
x = undefined; //undefined and null are very similar
</script>
In JavaScript, the most important types are objects and arrays. Chapter 6 introduces objects and Chapter 7 introduces arrays. Objects and arrays are so important in javascript. So much so that they can be seen everywhere in this book.
The code copy is as follows:
<script type="text/javascript">
//The most important type in javascript is the object
//Object is a collection of name/value pairs, or a collection of string values to mapped values.
var book = { //Objects are enclosed in curly braces
topic: "javascript", //The value of attribute "topic" is javascript
fat: true //The value of the property fat is true
}; //The curly braces on the right end.
//Access object properties through "." or "[]".
book.topic //=>"javascript"
book["fat"] //=>true Another way to get attributes,
book.author = "ahthw"; //Create a new attribute by assignment
book.content = {}; //{} is an empty object. It has no attributes
//javascript also supports arrays (lists indexed by arrays)
var primes = [2, 3, 5, 7]; // Has a combination of 4 values, the boundary is drawn by "["" "]"
primes[0] //=>2: The first object of the array, index is 0
primes.length //=>4, the number of elements in the array
primes[primes.length-1] //=>7: The last element in the array
primes[4] =9; //Add new elements by assignment
primes[4] =11;//Change existing elements by assignment
var empty = [];//Empty array, with 0 elements
empty.length //=>:0
//Arrays and objects can contain another array or object.
var point =[ //Array with two elements
{x:0,y:0}, //Each element is an object
{x:1,y:1}
];
var data ={ // An object containing two attributes
trial1:[[1,2],[3,4]], //Each object is an array
trial2:[[2,3],[4,5]] //The elements of the array are also arrays
};
</script>
The syntax of the above code that defines array elements through square brackets and defines the mapping relationship between object attribute names and attribute values through curly brackets. Chapter 4 is specifically introduced. Expressions are a phrase in JavaScript. This phrase can be calculated to obtain a value, and reference the value of object attributes or array elements through "," and "[]" to form an expression.
The most common expression writing method in javascript is operators like the following code (oprator)
The code copy is as follows:
//Operator as operator generates a new value
//The most common arithmetic operator
3+2 // =>5 Addition
3-2 // =>Subtraction
3*2 // =>Multiple
3/2 // =>Division
point[1].x -point[0].x //=>Complex operations can also work as usual
"3"+"2" // => 32. You can complete addition operations or string splicing.
//javascript defines some arithmetic operators as abbreviation
var count = 0; //Define a variable
count++; //Increase by 1
count--; //Decrement by 1
count +=2; //The auto-increment 2 is the same as "count = count + 2;"
count *=3 //Multiply 3. The same way as "count = count*3;" is written
count //=> 6: The variable name itself is also an expression
//The equality relationship operator is used to determine whether the two values are equal or not
//Unequal, greater than, less than operator operation result is true or false
var x=2,y=3; //The equal sign here means assignment, not relatively equal
x == y; //=>false equal
x! = y; //=> true
x < y; //=> true: less than
x <= y; //true is less than or equal to
x > y; //false greater than
x >= y; //false greater than or equal to
"two"=="three"; //false Two strings are not equal
"two" > "three"; //true The index of "tw" in the alphabet is greater than "th"
false == (x>y); //ture false =false;
//Logical operators are merged or inverse of boolean values
(x == 2)&&(y==3); //=>true Both comparisons are true.&& is "and"
(x > 3)||(y<3); //=> false Neither comparison is true. || means "or"
! (x == y); //=>true ! Indicates inverse search
If the "phrase" in javascript is an expression, then the whole sentence is called a statement, which will be explained in detail in Chapter 5.
In the above code, the lines ending with a semicolon are all statements. In a rough way, the expression only calculates one value (or the value it contains is not concerned with) but they change the running state of the program. In the above, variable declaration statements and assignment statements have been seen. Another type of statement is "control structure", such as conditional judgment and loop. After introducing the function, we give relevant example code.
Functions are javascript code snippets with names and parameters that can be defined and used multiple times at a time. Chapter 8 will formally explain the functions in detail. Like objects and arrays, functions are mentioned in many places in this book, so here are some simple example code.
The code copy is as follows:
//The function is a javascript code segment with treat parameters, which can be transferred multiple times
function plus1(x) { //Define a function named plus1 with the parameter x
return x + 1; //Return a value that is 1 larger than the passed in.
} //The code block of the function is the part wrapped in curly braces
plus1(y) //
var square =function(x){ //Function is a value that can be assigned to a variable
return x*x; // Calculate the value of the function
}; //The semicolon indicates the end of the assignment statement
square(plus1(y)); //One two functions in one expression
When the function and object are written together, the function is programmed with a "method" (method)
The code copy is as follows:
//When a function is assigned to an object's attribute, we call it
//"Method", all javascript objects contain methods
var a =[]; //Create an empty array
a.push(1,2,3); //Add objects to the array to the push() method
a.reverse(); //Data reversal
// document.write(a)
//We can define the method of sub-defined method, the keyword "this" is the definition method
Reference to the object of //, the example here is the array containing two point position information mentioned above.
points.dist = function(){ //Define a method to calculate the distance between two points
var p1 = this[0]; //Get the reference to the current array through this keyword
var p2 = this[1]; // and get the first two elements of the called array
var a =p2.x- p1.y; // Distance on x coordinate axis
var b =p2.y - p1.y; //Distance on the y-coordinate axis
return Math.sqrt(a * a + "we call it" + b * b); //Pythagorean theorem
}; //Math.sqrt() calculates square root
points.dist() // => Find the distance between two points
Now, give some examples of control statements. Here the example function contains the most common JavaScript control statements in the body.
The code copy is as follows:
// Here the javascript statement uses this syntax to include conditional judgment and loop
//The syntax similar to java c++ and other languages is used
function abs(x) { // Find the absolute value function
if (x >= 0) { //if
return x; //If true, execute this code
} else { //false execute
return -x;
}
}
function factprial(n) { //Computing the factorial
var product = 1; // Assign a value of 1 to product
While (n > 1) { // Loop to execute {} content when the value expression () is true
product *= n; //product = product * abbreviation
n--; // n = n-1 writing method
} //The loop ends
return product; //Return product
}
factprial(4) // =>24 1*4*3*2 document.write(factprial(4))
function factorial2(n) { // Another way to write a loop
var i, product = 1; //
for (i = 2; i <= n; i++) //Increase i from 2 to n
product *= i; //Loop body, when there is only one sentence of code in the loop body, omit {}
return product; // Calculate and return the good factorial;
}
factorial2(5) //document.write(factorial2(5)) =>120 : 1*2*3*4*5
Javascript is an object-oriented programming language, but it is very different from traditional page objects. Chapter 9 will explain the object-oriented JavaScript in detail. This chapter will have a lot of sample code, which is the longest chapter in this book.
Here is a simple example, this code shows how to define a class in javascript to represent points in geometry of 2D faces. The object instantiated in this class has a method called r() to calculate the distance from changing points to origin.
The code copy is as follows:
//Define a constructor to initialize a new point object
function Point(x, y) { //Constructors generally start with capital letters
this.x = x; //The keyword this refers to the initialized instance
this.y = y; //Storage function parameters as attributes of an object
}
//Create an instance using the new keyword and constructor
var p = new Point(1, 1); // Points 1, 1 in plane geometry,
//Assign value through the constructor prototype object
//To define methods for Point objects
Point.prototype.r = function() {
return Math.sqrt( //Return the square root of x square + y square
this.x * this.x + //this refers to the object that transports this method
this.y * this.y);
};
//Point's instance object p (and all point instance objects) inherits the method r()
pr() // => 1.4142135623730951 /document.write(pr())
Chapter 9 is the essence of the first part . The subsequent chapters have been sporadically extended, which will lead us to the end of our exploration of JavaScript.
Chapter 10 mainly talks about text matching patterns performed by regular expressions.
Chapter 11 The main language core subset and superset of gypsum javascript .
Before entering the content of JavaScript on the client, Chapter 12 we only introduce two JavaScript running environments outside the web.
2. Client javascript
There are many cross-references to the content knowledge points in the core part of the javascript language, and the sense of knowledge is not clear. The content orchestration of JavaScript on the client side has changed a lot. According to this chapter, you can use javascript in a web browser. (But if you want to learn JavaScript by reading this book, you can't just focus on the second part) Chapter 13 is the first part of the second part, which introduces how to make JavaScript run in a web browser. Chapter 14 explains web browser scripting technology and covers an important global function of the client javascipt.
For example:
The code copy is as follows:
function moveon() {
// Ask a question through the dialog box
var answer = confirm("Are you ready?");
//Click OK and the browser will load a new page
if (answer) window.location = "http://www.baidu.com";
}
//Execute this function after 1 minute (60000 milliseconds)
setTimeout(moveon,300);
Chapter 15 will tell you how JavaScript can manipulate the HTML style to define the display method of content . The content of Chapter 15 will be more pragmatic. Through scripts, it will show how to select specific web page elements, how to set attributes for html elements, if the content of the element is modified, and how to add new nodes to the document
The following example function shows if you find and modify the basic article content
The code copy is as follows:
//A specified information in the document and the area tree is over debugging information
//If this element does not exist on the document, create a
function debug(msg) {
// Find the debugging part of the document by viewing the id attribute of the html element
var log = document.getElementById("debuglog");
//If the element does not exist, create a
if (!log) {
log = document.createElement("div"); //Create a new div element
log.id = "debuglog"; // Assign value to the id of each element
log.innerHTML = "<h1>Debug Log</h1>"; //Customize the initial content
document.body.appendChild(log); //Add it to the end of the document
}
//Include the message in <pre> and add it to the log
var pre = document.createElement("pre"); //Create pre element
var text = document.createElement(msg); //Include msg on a text node
pre.appendChild(text); // Add text to pre
log.appendChild(pre); //pre add to log
}
Chapter 16 will talk about how to use javascript to operate elements , which usually uses the style and class attributes of the element.
The code copy is as follows:
function hide(e, reflow) { //Manipulate elements and hide elements e through jvascript
if (reflow) { //If the second parameter is true
e.style.display = "none" //Hide this element, and the space it takes up is also sold
} else {
e.style.visibility = "hidden"; //Hide e, retaining the space it takes
}
}
function highlight(e) { // Highlight e by setting css
if (!e.className) e.className = "highcss";
else
e.className += "highcss";
}
The content and css style of elements can be controlled through JavaScript, and the document behavior can also be defined through event handlers. Event handling is a javascript function registered in the browser center. When a specific event occurs, the browser can call this function.
Usually the types of events we focus on are mouse clicks and keyboard key events (smartphones are various touch events). Or when the browser completes the document loading, a person event will be triggered when the user changes the size of the window or when the user enters data into the form.
Chapter 17 will describe in detail how to define, register time handlers, and how the browser calls them when events occur.
The easiest way to customize event handlers is to bind a callback to the attribute prefixed by html. When writing some simple program tests, the most practical way is to bind a callback to the "onclick" handler. Assuming that the above debug() and hide() functions are saved to the debug.js and hide.js files above, you can simply specify an event handler for the onclick attribute. as follows
The code copy is as follows:
<script type="text/javascript">
//A specified information in the document and the area tree is over debugging information
//If this element does not exist on the document, create a
function debug(msg) {
// Find the debugging part of the document by viewing the id attribute of the html element
var log = document.getElementById("debuglog");
//If the element does not exist, create a
if (!log) {
log = document.createElement("div"); //Create a new div element
log.id = "debuglog"; // Assign value to the id of each element
log.innerHTML = "<h1>Debug Log</h1>"; //Customize the initial content
document.body.appendChild(log); //Add it to the end of the document
}
//Include the message in <pre> and add it to the log
var pre = document.createElement("pre"); //Create pre element
var text = document.createElement(msg); //Include msg on a text node
pre.appendChild(text); // Add text to pre
log.appendChild(pre); //pre add to log
}
function hide(e, reflow) { //Manipulate elements and hide elements e through jvascript
if (reflow) { //If the second parameter is true
e.style.display = "none" //Hide this element, and the space it takes up is also sold
} else {
e.style.visibility = "hidden"; //Hide e, retaining the space it takes
}
}
function highlight(e) { // Highlight e by setting css
if (!e.className) e.className = "highcss";
else
e.className += "highcss";
}
</script>
hello
<button onclick="hide(this,true); debug('hide button 1');">hide1</button>
<button onclick="hide(this);debug('hide button 2');">hide2</butotn>
The following client javascript uses events, which gives a very important event: the "load" event registers an event to handle Chenxing. Colleagues also show a more advanced way to register "click" event handlers
The code copy is as follows:
<script type="text/javascript">
//The "load" event can only be fired after the document is loaded
//If you usually need to wait for the load event to occur before you can execute javascript code
window.onload = function() {
//Find all img tags in the document
var images = document.getElementsByTagName("img");
//Transfer through images and add a handler to the click event of each node
//Hide the picture when clicking on it
for (var i = 0; i < images.length; i++) {
var imge = images[i];
if (imge.addEventListener) //Another way to register time handler
imge.addEventListener("click", hide, false);
else //Compatible with previous operations of ie8
imge.attachEvent("onclick", hide);
}
//This is the above registered event processing function
function hide(evnet) {
event.target.style.visibility = "hidden";
}
};
</script>
Chapter 15-17 tells how to use JavaScript to control the content, style and behavior of web pages (event processing). This chapter discusses the API a bit complicated, and it has poor browser compatibility so far. This is why many JavaScript programmers choose to use "library" or "framework" to simplify their coding work. The most popular one is jQuery. Chapter 19 introduces jQuery library
The code copy is as follows:
function debug(msg) {
var log = $("#debuglog");
if (log.length == 0) {
log = $("<div id='debuglog'><h1>debuglog</h1></div>");
log.appendTo(document.body);
}
document.write(log)
log.append($("<pre/>").text(msg));
};
The four chapters of the second part we mentioned are all discussed around web pages. The subsequent four chapters will focus on the store and turn to web applications. These contents are not discussed how to write and manipulate content. Styles and thriving scripts use web browsers to render documents; instead explain how to use web browsers as an application platform. And describes APIs for supporting more complex and refined client web applications and modern browsers.
Chapter 18 explains how to use javascript to initiate http requests.
Chapter 20 describes the data storage mechanism and the session state maintenance of client applications . Chapter 21 covers the new generation of application APIs/network storage graphics driven by HTML5. These are based on browser development that supports new APIs. Zhejiang is your most exciting moment as a javascript programmer. There is not much sample code in the last 4 chapters. The following example uses these new APIs.