2015年9月17日星期四

[笔记] Speaking JavaScript Chapter 9 Operators

1. Equality Operators


Equality is not customizable. Operators can't be overloaded in JavaScript, and you can't customize how equality works. There are some operations where you often need to influence comparison-for example, Array.prototype.sort(). That method optionally accepts a callback that perform all comparisons between elements.

Pitfall: NaN !== NaN

Normal(Lenient) Equality (==, !=)

The following comparison ensures that x is neither undefined nor null:

if (x != null) ...


Use case: working with numbers in strings

if (x == 123) ...

The preceding checks whether x is either 123 or '123'. It is better to be explicit:

if (Number(x) === 123) ...


Use case: comparing wrapper instances with primitives

> 'abc' == new String('abc')
true

> new String('abc') == new String('abc')
false

Lenient equality does not work between wrapped primitives.

2. The Plus Operator


You evaluate an addition:

value1 + value2
by taking the following steps:
(1) Ensure that both operands are primitives. Objects obj are converted to primitives
via the internal operation ToPrimitive(obj) (refer to “Algorithm: ToPrimitive()—
Converting a Value to a Primitive” on page 79), which calls obj.valueOf() and,
possibly, obj.toString() to do so. For dates, obj.toString() is called first.
(2) If either operand is a string, then convert both to strings and return the concatenation
of the results.
(3) Otherwise, convert both operands to numbers and return the sum of the results.


3. Special Operators


What is void for?
(1) void 0 as a synonym for undefined
(2) Discarding the result of an expression
If you want to open a new window without changing the currently displayed content, you can do the following:
javascript:void window.open("http://example.com/")


Pitfall: typeof null
Unfortunately, typeof null is 'object'. The following function checks whether value is an object:
function isObject(value) {
return (value !== null
&& (typeof value === 'object'
|| typeof value === 'function'));
}

2015年9月15日星期二

[笔记] Speaking JavaScript Chapter 8 Values

1.JavaScript's Type System

JavaScript has only six types: undefined, null Boolean, String, Number, and Object.

1.1 Static versus Dynamic
static: at compile time
dynamic: at runtime

Object foo = "abc";

The static type of foo is Object; its dynamic type is String.
JavaScript is dynamically typed; types of variables are generally not known at compile time.

coerce: implicit type conversion

2. Primitive Values versus Objects

(1) The primitive values are booleans, numbers, strings, null and undefined.
(2) All other values are objects.

The most common kinds of objects are: palin objects/ arrays/ regex
Objects have the following characteristics: Compared by reference/ Mutable by default/ User-extensible

Changing undefined:

if (x === void 0) // always safe

3. Wrapper Objects

The three primitive types boolean, number, and  string have corresponding constructors: Boolean, Number, String. Their instance (so-called wrapper objects) contain (wrap) primitive values. The constructors can be used in two ways:

(1) As constructors:

> typeof new String('abc')
'object'
> new String('abc') === 'abc'
false

(2) As functions:

> String(123)
'123'

It is considered a best practice to avoid wrapper objects

Primitives Borrow Their Methods from Wrappers

> 'abc'.charAt == String.prototype.charAt
true

2015年9月14日星期一

[笔记] Speaking JavaScript Chapter 7 JavaScript's Syntax

1. Expression Versus Statements

An expression produces a value and can be written wherever a value is expected.
Wherever JavaScript expects a statement, you can also write an expression. Such a statement is called expression statement. The reverse does not hold: you cannot write a statement where JavaScript expects an expression. For example, an if statement cannot become the argument of a function.

conditional operator:
var salutation = (male ? 'Mr.' : 'Mrs.');

Using ambiguous expressions as statements: JavaScript does not let you use object literals and function expressions as statements. That is, expression statements must not start with: A curly brace / The keyword function

Immediately invoking a function expression

> (function () { return 'abc'}())
'abc'

If you omit the parentheses, you get a syntax error, because JavaScript see a function declaration, which can't be anonymous. If you add a name, you also get a syntax error, because function declaration can't be immediately invoked.


2. Rules for Using Semicolons

Normally, statements are terminated by semicolons.
The following statements are not terminated by semicolons if they end with a block.
Loops: for, while(but not do-while)
Branching: if, switch, try
Function declarations(but not function expressions)

while versus do-while:

while (a > 0) {
a--;
} // no semicolon

do {
a--;
} while (a > 0);

function declaration versus function expression:

function foo() {
//...
} // no semicolon

var foo = function () {
//...
};

3. Legal Identifiers

Reserved words are part of the syntax and can't be used as variable names.

4. Invoking Methods on Number Literals

It is important to distinguish between the floating-point dot and the method invocation dot. You can't write 1.toString(); you must use the one of the following altrnatives:
1..toString()
1 .toString() // space before dot
(1).toString()
1.0.toString()

5. Strict Mode

The normal(nonstrict) mode is sometimes called "sloppy mode".
In strict mode, all variables must be expicitly declared.
In strict mode, all functions must be declared at the top level of a scope.

function strictFunc() {
'use strict';
{
//Syntax Error:
function nested() {

}
}
}

function strictFunc() {
'use strict';
{
//OK
var nested = function () {
};
}
}

2015年9月8日星期二

[笔记] Speaking JavaScript Chapter 1

Speaking JavaScript

Preface

Don't get bogged down by the details.
JavaScript Command Lines: Node.js

Chapter 1: Basic JavaScript

1.1 Syntax

1.1.1 Overview of Syntax

// two slashes start single-line comments

var x; // declaring a variable

x = 3 + y; // assigning a value to the variable 'x'

foo(x, y); // calling function 'foo' with parameters 'x' and 'y'
obj.bar(3); // calling method 'bar' for object 'obj'

//A conditional statement
if (x === 0) { // Is 'x' equal to zero?
x = 123;
}

//Defining function 'baz' with parameters 'a' and 'b'
function baz(a, b) {
return a + b;
}

Note the two different uses of the equal sign:
(1) A single equals sign (=) is used to assign a value to a variable.
(2) A triple equal sign (===) is used to compare two values.


1.1.2 Statements v. Expression

statement: do things
expression: value

JS has two different ways to do if-then-else
(1) statement:
var x;
if (y >= 0) {
x = y;
} else {
x = -y;
}
(2) expression
var x = y >= 0 ? y : -y;


1.1.3 Semicolons: recommended

semicolons terminate statements, but not blocks. There is one case where you will see a semicolon after a block: a function expression is an expression that ends with a block.

var f = function () { }; // function expr. inside var decl.


1.2 Values

1.2.1 Primitive Values v. Objects

JavaScript makes a somewhat arbitrary distinction between values:
(1) The primitive values are booleans, numbers, strings, null and undefined.
(2) All other values are objects.

A major difference between the two is how they are compared; each object has a unique identity and is only(strictly) equal to itself.
In contrast, all primitive values encoding the same value are considered the same.

1.2.2 Primitive Values

(1) Compared by value: the "content" is compared
e.g. 3 === 3 , 'abc' === 'abc'

(2) Always immutable: properties can't be changed

> var str = 'abc';
> str.length = 1; // try to change property 'length'
> str.length // no effect
3

1.2.3 Objects

(1) Plain Objects
{
firstName: 'Jane',
lastName: 'Doe'
}

(2) Arrays
['apple', 'banana', 'cherry']

(3) Regular Expression
/^a+b+$/

(4) Characteristics
Comapred Reference:
1)
> {} === {}
false

2)
> var obj1 = {};
> var obj2 = obj1;
> obj1 === obj2;
true

Mutable by Default:
> var obj = {};
> obj.foo = 123; // add property 'foo'
> obj.foo
123

1.2.4 undefined and null

undefined: no value
null: no object

checking for undefined and null:
if (!x) {...}

1.2.5 typeof and instanceof

(1) type of value
> typeof true
'boolean'
>typeof null
'object' // this is a bug and cannot be fixed

(2) instance of
> {} instanceof Object
true

1.3 Booleans

JavaScript has two kinds of equalty:
(1) Normal, or "lenient", (in) equalty: == and !=
(2) Strict (in)equalty: === and !==
Normal equality is considered (too) many values to be equal (p84) which hide bugs. Therefore, always using strict equality is recommended.

1.4 Numbers

All numbers in JavaScript are floating-point
Special Numbers:
(1) NaN ("Not a Number")
> Number('xyz')
NaN
(2) Infinity: Infinity is LARGER and SMALLER than any other number
> 3 / 0
Infinity

1.5 Operators

+-*/%++--
The global object Math(P31) provides more arithmatic operators

1.6 Strings

slice/trim/indexOf

1.7 Functions

function add(param1, param2) {
return param1 + param2;
}

> add(6, 1)
7
> add('a', 'b')
'ab'

Another way of defining add() is:

var add = function (param1, param2) {
return param1 + param2;
};

1.7.1 Function and var declaration are hoisted, while assignments performed by them are not.

function foo() {
bar(); // OK, bar is hoisted
function bar() {
...
}
}

function foo() {
bar(); // Not OK, bar is still undefined
var bar = function() {
...
}
}

1.7.2 You can call any function in JavaScript with an arbitrary amount of arguments; the language will never complain.

1.7.3 special variable argument

1.8 Strict Mode

1.9 Variables Are Function-Scoped, Hoisted

1.10 Closure

Each function stays connected to the variables of the functions that surround it, even after it leaves the scope in which it is created.

function createIncrementor(start) {
return function() { // (1)
start++;
return start;
}
}

The function starting in line (1) leaves the context in which it is created, but stays connected to a live version of start:

> var inc = cerateIncrement(5);
> inc()
6
> inc()
7
> inc()
8

A closure is a function plus the connection to the variables of its surrounding scopes. Thus, what createIncrementor() returns a closure.

1.11 Objects and Constructors

1.11.1 Single Objects

You could consider an object to be a set of properties, where each property is a (key, value) pair. The key is a string, and the value is any JavaScript value.

'use strict'
var jane = {
name: 'Jane',

describe: function () {
return 'Person named' + this.name;
}
}

> jane.name // get
'Jane'
> jane.name = 'John'; // set
> jane.newProperty = 'abc'; // property created automatically

The in operator checks whether a property exists:

> 'newProperty' in jane
true
> 'foo' in jane
false

The delete operator removes a property:

> delete jane.newProperty
true

1.11.2 Arbitrary Property Keys

Use square brackets to get and set the property:

> var obj = { hello: 'world' };
> var x = 'hello';

> obj[x]
'world'
> obj['hel' + 'lo']
'world'

1.11.3 Extracting Methods

If you extract a method, it loses its connection with the object. On its own, the function is not a method anymore, and this has the value undefined (in strict mode).

Extract the method describe from jane, put it into a variable func, and call it. However, that doesn't work:

> var func = jane.describe;
> func()
TypeError: Cannot read property 'name' of undefined

Solution: use the method bind(). It creates a new function whose this always has the given value.

> var func2 = jane.describe.bind(jane);
> func2()
'Person named Jane'

1.11.4 Functions inside a method (这里有点没搞懂)

Every function has its own special variable this. This is inconvenient if you nest a function inside a method, because you can't access the method's this from the function. The following is an example where we call forEach with a function to iterate over an array:

var jane = {
name: 'Jane',
friends: [ 'Tarzan', 'Cheeta' ],
logHiToFriends: function () {
'use strict';
this.friends.forEach(function (friend) {
// 'this' is undefined here
console.log(this.name + ' says hi to ' + friend);
});
}
}

> jane.logHiToFriends()
TypeError: Cannot read property 'name' of undefined

Solution 1: store this in a different variable

logHiToFriends: function () {
'use strict';
var that = this;
this.friends.forEach(function (friend) {
console.log(that.name + ' says hi to ' + friend);
});
}

Solution 2: forEach has a second parameter that allows you to provide a value for this:

logHiToFriends: function () {
'use strict';
this.firends.forEach(function (friend) {
console.log(that.name + ' says hi to ' + friend);
}, this);
}

Attention: Function expression are often used as arguments in function calls in JavaScript. Always be careful when you refer to this from one of those function expressions.

1.11.5 Constructors: Factories for Objects

// Set up instance data
function Point(x, y) {
this.x = x;
this.y = y;
}

//Method
Point.prototyoe.dist = function () {
return Math.sqrt(this.x*this.x + this.y*this.y);
}

> var p = new Point(3, 5);
> p.x
3
> p.dist()
5.83....

p is an instance of Point:

> p instanceof Point
true

1.12 Arrays

Array Methods:
slice/push/pop/shift/indexOf/join

map creates a new array by applying a function to each element of an existing array:
> [1,2,3].map(function (x) { return  x*x })
[ 1, 4, 9 ]

1.13 Regular Expression(Chapter 19)

Method: test(): Is There a Match?
> /^a+b+$/.test('aaab')
true
> /^a+b+$/.test('aaa')
false

2015年9月6日星期日

[笔记][Computer Networks] Chapter 1

Computer Networks (Fifth Edition)
Chapter 1

Difference between distributed system and computer network:
In a distributed system, a collection of independent computers appears to its users as a single coherent system. Usually, it has a single model of paradigm that it presents to the users. Of a layer of software on top of the operating system, called middleware, is responsible for implementing this model. A well-known example of a distributed system is the World Wide Web. It runs on top of the Internet and presents a model in which everything looks like a document.
In a computer network, this coherence, model and software are absent. Users are exposed to actual machines, without any attempt by the system to make the machine look and act in a coherent way. If the machines have different hardware or different operating systems, this is fully visible to the users. If a user wants to run a program on a remote machine, he has to log onto that machine and run it here.

1.1 Uses of Computer Networks

Client-Server Model:
In this model, the data are stored on powerful computers called servers. Often there are centrally housed and maintained by a system administrator.
In contrast, the employees have simpler machines, called client, on their desk, with which they access remote data, for example, to include in spreadsheet they are constructing.
Peer-to-peer communication:
In this form, individuals who form a loose group can communicate with others in the group. Every person can, in principle, communicate with one or more other people; there is no fixed division into client and servers.

1.2 Network Hardware

Broadly speaking, there are two types of transmission technology that are in widespread use: broadcast links and point-to-point link.
Point-to-pint links: exactly one sender and exactly one receiver, packets may have to first visit one or more intermediate machines, multiple routes (finding a good one is important)
Broadcast links: packets sent by any machine are received by all the others
Classification of Network by Scale:
(1) PAN: Bluetooth to connect mouse to computer, RFID on smart card
(2) LAN: IEEE 802.11(WiFi), switched Ethernet
Static and dynamic allocation of channel
(3) MAN: cable television networks
(4) WAN: span a country or continent

1.3 Network Software


Fig 1-13
The entities comprising the corresponding layers on different machines are called peers. It is peers that communicate by using the protocol to talk to each other.
Each layer passes data and control information to the layer immediately below it. Between each adjacent layer is an interface.


Fig 1-15
Service: Connection-oriented vs. connection-less
The relationship of Services to Protocols:
A service is a set of primitives (operations) that a layer provides to the layer above it. A service relates to an interface between two layers, with the lower layer being the service provider and the upper layer being the service user.
A protocol, in the contrast, is a set of rules governing the format and meaning of the packets, or messages that are exchanged by the peer entities within a layer.

1.4 Reference Models

1.4.1 The OSI Reference Model (seven layers)



(1) The Physical Layer: transmitting raw bits over a communication channel
(2) The Data Link Layer: transform a raw transmission facility into a line that appears free of undetected transmission errors.
(3) The Network Layer: controls the operation of the subnet. (determine how packets are routed from source to destination)
(4) The Transport Layer: is to accept data from above it, split it up into units if need be, pass these to the network layer, and ensure that the pieces all arrive correctly at the other end.
(5) The Session Layer: allows users on different machines to establish sessions between them
(6) The Presentation Layer: concerned with the syntax and semantics of the information transmitted
(7) The Application Layer: contains a variety of protocols that are commonly used by users, e.g. HTTP

1.4.2 The TCP/IP Reference Model
Fig 1-21