《Javascript & JQuery interactive front-end web development》 by Jon Duckette 读书笔记-未完待续

There are many inconsistencies between browsers that affect JavaScript developers. jQuery will help you deal with cross-browser inconsistencies (it is one of the major reasons why jQuery rapidly gained popularity amongst web developers).

Computers use data to create models of things in the real world. The events, methods, and properties of an object all relate to each other: Events can trigger methods, and methods can retrieve or update an object's properties.

The browser represents each window or tab using a window object. The location property of the window object will tell you the URL of the current page.

The current web page loaded into each window is modelled using a document object.
The title property of the document object tells you what is between the opening <title> and closing </title> tag for that web page, and the lastModified property of the document object tells you the date this page was last updated.

Some statements are surrounded by curly braces; these are known as code blocks. The closing curly brace is not followed by a semicolon.

Unlike some other programming languages, when declaring a variable in JavaScript, you do not need to specify what type of data it will hold.

Quotes for string literals should be straight (not curly) quotes:

Because strings can live in single or double quotes, if you just want to use double quotes in the string, you could surround the entire string in single quotes. If you just want to use single quotes in the string, you could surround the string in double quotes.

A technique called escaping the quotation characters is done by using a backwards slash (or "backslash") before any type of quote mark that appears within a string. The backwards slash tells the interpreter that the following character is part of the string, rather than the end of it.

---------------------
// Write total into the element with i d of cost
/*a variable can be used to hold a reference to an element in the HTML page. This allows you to work directly with the element stored in that variable.*/
var el = document .getElementByld( ' cost');
el . textCont ent = '$' +total;
------------------
Variable name can contain letters, numbers, dollar sign ($), or an underscore (_). But, you must not use a dash (-) or a period (.) in a variable name.

The values in the array do not need to be the same data type, so you can store a string, a number and a Boolean all in the same array.

Rather than creating an array literal, an array can be created using a different technique called an array constructor. This uses the new keyword followed by Array(); the values are then specified in parentheses (not square brackets), and each value is separated by a comma. 
----------------
var colors = new Array('white', 
                       'black',
                       'custom');

alert(colors.length);//show how many elements are in an array;;length is a property, not a function, so do not add () after the keyword "length".

---------------------
An expression evaluates into (results in) a single value.
Technically, undefined is a data type like a number, string, or Boolean.
--------------
var score = 'seven';
var score2 = 'nine';
var total = score * score2;
alert(total);//NaN
--------------
Functions consist of a series of statements that have been grouped together because they perform a specific task. A method is the same as a function, except methods are created inside (and are part of) an object.

Programming languages often rely upon on name/value pairs. The function has a name and the value is the code block (which consists of statements). When you call the function by its name, those statements will run.
You can also have anonymous functions. They do not have a name, so they cannot be called. Instead, they are executed as soon as the interpreter comes across them.

The function acts like a store; it holds the statements that are contained in the curly braces until you are ready to use them. Those statements are not run until the function is called.

Sometimes you will see a function called before it has been declared. This still works because the interpreter runs through a script before executing each statement, so it will know that a function declaration appears later in the script.

-----------------

//Functions can return more than one value using an array.
    
function getSize (width, height, depth) {
    var area = width * height;
    var volume = width * height * depth;
    var sizes= [area , volume];
    return sizes;
}
var areaOne = getSize (3, 2, 3)[0];
console.log('areaOne is: ' + areaOne);
var volumeOne = getSize (3, 2, 3)[1];
console.log('volumeOne is: ' + volumeOne);
---------------
Expressions produce a value. They can be used where values are expected. If a function is placed where a browser expects to see an expression, (e.g., as an argument to a function), then it gets treated as an expression.
----------
/*If you put a function where the interpreter would expect to see an expression, then it is treated as an expression, and it is known as a function expression. In function expressions, the name is usually omitted. A function with no name is called an anonymous function. Below, the function is stored in a variable called area. It can be called like any function created with a function declaration.*/
var area = function(width, height) {
    return width * height;
};
var size = area(3, 4) ;
console.log('size is: ' + size);
-------------
/*The variable called area will hold the value returned from the function (rather than storing the function itself so that it can be called later).*/
var area =(function() {
    var width = 3;
    var height = 2;
    return width * height;
}());
console.log(area);
/*The final parentheses after the closing curly brace of the code block tell the interpreter to call the function immediately. The grouping operators are parentheses there to ensure the intrepreter treats this as an expression.
You may see the final parentheses in an IIFE placed after the closing grouping operator but it is commonly considered better practice to place the final parentheses before the closing grouping operator, as shown in the code above.
IIFEs are commonly used as a wrapper around a set of code. Any variables declared within that anonymous function are effectively protected from variables in other scripts that might have the same name.*/    
-------------
function getArea(width, height) {
    //a variable used without the var keyword, the variable will be treated as a global variable (this is considered bad practice).
    randomNum = 1;
    area = width * height;
    return area;
}

getArea(2,3);
var wallSize = getArea(3, 2);

console.log(wallSize);
console.log(randomNum);
--------------
If a variable is part of an object, it is called a property.
If a function is part of an object, it is called a method.
------------
You can also access the properties of an object (but not its methods) using square bracket syntax. This time the object name is followed by square brackets, and the property name is inside them. This notation is used most commonly used when the name of the property is a number (technically allowed, but should generally be avoided) or a variable is being used in place of the property name.
---------------
// Set up the object
var hotel = new Object();

hotel.name = 'Park';
hotel.rooms = 120;
hotel.booked = 77;
hotel.checkAvailability = function() {
  return this.rooms - this.booked;  
};

console.log(hotel.name, hotel.checkAvailability());

/*this syntax can be used to add properties and methods to any object you have created (no matter which notation you used to create it).
To create an empty object using literal notation use:
var hotel = {}
The curly brackets create an empty object.*/
-----------------
// Create the template for objects that are hotels
function Hotel(name, rooms, booked) {
  this.name = name;
  this.rooms = rooms;
  this.booked = booked;
  this.checkAvailability = function() {
    return this.rooms - this.booked;
  };
}


// Create two hotel objects
var quayHotel = new Hotel('Quay', 40, 25);
var parkHotel = new Hotel('Park', 120, 77);

console.log(quayHotel.name);
console.log(parkHotel.name);
-----------
/*When a function is created at the top level of a script (that is, not inside another object or function), then it is in the global scope or global context.
The default object in this context is the window object, so when this is used inside a function in the global context it refers to the window object.
Below, this is being used to return properties of the window object.
Under the hood, the this keyword is a reference to the object that the function is created inside.
*/

function windowSize() {
  var width = this.innerWidth;
  var height = this.innerHeight;
  return [height, width];
}
currentWindowSize=windowSize();
console.log(currentWindowSize);

------------------
/*All global variables also become properties of the window object, so when a function is in the global context, you can access global variables using the window object, as well as its other properties.
Here, the showWidth() function is in global scope, and this.width refers to the width variable*/

var width = 600 ; 
var shape = {width: 300};
var showWidth = function() {
    alert(this.width);
};
showWidth();
-----------------
/*When a function is defined inside an object, it becomes a method. In a method, this refers to the containing object.
In the example below, the getArea() method appears inside the shape object, so this refers to the shape object it is contained in*/
var shape = {
width : 600,
height : 400,
getArea : function() {
    return this.width * this.height;
//same as:    return shape.width * shape.height;
}
};

console.log(shape.getArea());
-----------------
/*The last but one line indicates that the showWidth() function is used as a method of the shape object. The method is given a different name: getWidth().
When the getWidth() method is called, even though it uses the showWidth() function, this now refers to the shape object, not the global context (and this.width refers to the width property of the shape object). So it writes a value of 300 to the page.*/

var width = 600;
var shape= {width : 300};
var showWidth = function () {
    alert(this.width);
};
shape.getWidth = showWidth;
shape.getWidth();//output 300

-------------------
Two pages back, it was noted that an array can hold a set of objects, or that the property of an object could be an array. It is also possible for the property of an object to be another object. When an object is nested inside another object, you may hear it referred to as a child object.
------------------
//The document object's lastModified property will tell you the date that the page was last updated
console.log(document.lastModified);
-------------
//The String object's toUpperCase() method makes all letters in the following variable uppercase.
var aString ="originally written in lowercase."

console.log(aString.toUpperCase());
----------------
console.log(Math.PI);
--------------
Child objects are stored as properties of their parent object. So dot notation is used to access them, just like you would access any other property of that object.
--------------
// Find the width of the browser window
window.innerWidth;
// Find the height of the browser window
window.innerHeight;
// Find the width of the computer screen
window.screen.width;
// Find the height of the computer screen
window.screen.height;
----------------
The window object's alert() method is used to create a dialog box shown on top of the page. It is known as an alert box. Although this is a method of the window object, you may see it used on its own (as shown here) because the window object is treated as the default object if none is specified.
-----------------
//title of current document
console.log(document.title);
//returns string contains URL of current document
console.log(document.URL);
//returns domains of current document
console.log(document.domain);
-------------
The HTML <hr> element represents a thematic break between paragraph-level elements: for example, a change of scene in a story, or a shift of topic within a section.
Historically, this has been presented as a horizontal rule or line. While it may still be displayed as a horizontal rule in visual browsers, this element is now defined in semantic terms, rather than presentational terms, so if you wish to draw a horizontal line, you should do so using appropriate CSS.

it can be confusing to discover that a simple value (like a string, a number, or a Boolean) can have methods and properties. Under the hood, JavaScript treats every variable as an object in its own right.

Technically, functions are also objects. But they have an additional feature: they are callable, which means you can tell the interpreter when you want to execute the statements that it contains.
-------------
var randomNumber = 12.3456234567;
console.log(typeof(randomNumber));//number
console.log(randomNumber.toFixed(2));//12.35,a  string is returned, because fractions cannot always be accurately represented using floating point numbers.
console.log(typeof(randomNumber.toFixed(2)));//string
console.log(randomNumber.toPrecision(5));// 12.346
console.log(typeof(randomNumber.toPrecision(5)));// string
console.log(randomNumber.toExponential(2));//1.23e+1
console.log(typeof(randomNumber.toExponential(2)));//string
-------------------
//Math is known as a global object. 
console.log(Math.round(2.6));//round number to the nearest integer 3
console.log(Math.round(3.1));//round number to the nearest integer 3
console.log(Math.ceil(3.1));//round number up to the nearest integer 4
console.log(Math.floor(3.1));//round number down to the nearest integer 3
console.log(Math.random());//Generates a random number between 0 (inclusive) and 1(not inclusive).
----------------
// Create a variable to hold a random number between 1 and 10
/*Using the floor() method ensures that the number is always rounded down to the nearest integer, and you can then add 1 to ensure the number is between 1 and 10.*/
var randomNum = Math.floor((Math.random() * 10) + 1);
--------------
In JavaScript, dates are stored as a number: specifically the number of milliseconds since midnight on January 1, 1970.
---------------
// Create a variable to hold a new Date object (defaults to now)
var today = new Date();
var Day = today.getDate();//return the day of the month(1-31);
today.setDate(12);//set the day of the date
console.log(today.getDate());
console.log(today.toDateString());//return date as a human-readable string
console.log(today.toTimeString());//return time as a human-readable string
console.log(today.toString())//return date and time as a human-readable string
----------------
//set a date using the following string format
var aDateCreated = new Date('Apr 16, 1996 15:45:55');
-----------
Placing script inside an immediately invoked function expression helps protect the scope of variables.

Every value can be treated as true or false even if it is not a Boolean true or false value.

-----------------
var pass = 50;   // Pass mark
var score = 90;  // Score

// Check if the user has passed
var hasPassed = score >= pass;
console.log(hasPassed);//true
--------------
var aBooleanValue = true;
console.log(typeof(aBooleanValue));//boolean
-----------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值