The JavaScript Programming Language - Sách Javascript C A Yahoo!
The JavaScript Programming Language - Sách Javascript C A Yahoo!
Programming Language
Douglas Crockford
Overview
• History
• Language
• Advanced Features
• Platforms
• Standards
• Style
The World's Most
Misunderstood
Programming Language
Sources of
Misunderstanding
• The Name
• Mispositioning
• Design Errors
• Bad Implementations
• The Browser
• Bad Books
• Substandard Standard
• JavaScript is a Functional
Language
History
• 1992
Oak, Gosling at Sun & FirstPerson
• 1995
HotJava
LiveScript, Eich at Netscape
• 1996
JScript at Microsoft
• 1998
ECMAScript
Not a Web Toy
• It is a real language
parseInt("08") === 0
parseInt("08", 10) === 8
Math
• Math object is modeled on Java's Math class.
• It contains
abs absolute value
floor integer
log logarithm
max maximum
pow raise to a power
random random number
round nearest integer
sin sine
sqrt square root
Strings
• Sequence of 0 or more 16-bit
characters
UCS-2, not quite UTF-16
No awareness of surrogate pairs
• No separate character type
Characters are represented as strings with
a length of 1
• Strings are immutable
• Similar strings are equal ( == )
• String literals can use single or double
quotes
String length
• string.length
/*
slashstar
block
comment
*/
Operators
• Arithmetic
+ - * / %
• Comparison
== != < > <= >=
• Logical
&& || !
• Bitwise
& | ^ >> >>> <<
Ternary
?:
+
• Addition and concatenation
• If both operands are numbers,
then
add them
else
convert them both to strings
concatenate them
'$' + 3 + 4 = '$34'
+
• Unary operator can convert
strings to numbers
+"42" = 42
• Also
Number("42") = 42
• Also
parseInt("42", 10) = 42
+"3" + (+"4") = 7
/
• Division of two integers can
produce a non-integer result
10 / 3 = 3.3333333333333335
== !=
• Equal and not equal
}
For statement
• Iterate through all of the members of
an object:
}
}
Switch statement
• Multiway branch
throw {
name: exceptionName,
message: reason
};
Try statement
try {
...
} catch (e) {
switch (e.name) {
case 'Error':
...
break;
default:
throw e;
}
}
Try Statement
• The JavaScript implementation
can produce these exception
names:
'Error'
'EvalError'
'RangeError'
'SyntaxError'
'TypeError'
'URIError'
With statement
• Intended as a with (o) {
short-hand foo = null;
}
• Ambiguous
o.foo = null;
• Error-prone
foo = null;
• Don't use it
Function statement
function name(parameters) {
statements;
}
Var statement
• Defines variables within a
function.
var name;
var nrErrors = 0;
var a, b, c;
Scope
• In JavaScript, {blocks} do not
have scope.
• , separates pairs
"goto" "Jail"
"grade" "A"
"level" 3
myFunction({
type: 'rect',
width: 1920,
height: 1080
});
throw {
name: 'error',
message: 'out of bounds'
Object Literals
function SuperDiv(width, height,
left, top, zIndex, position,
color, visibility, html,
cssClass)
function SuperDiv(spec)
Object Augmentation
• New members can be added to
any object by simple assignment
myObject[name] = value;
Linkage
• Objects can be created with a secret
link to another object.
myNewObject
myOldObject
"name" "Jack B. Nimble"
"goto" "Jail"
"grade" "A"
"level" 3
Linkage
myNewObject.name = "Tom Piperson";
myNewObject.level += 1;
myNewObject.crime = 'pignapping';
"level" 4
"crime" "pignapping"
"goto" "Jail"
"grade" "A"
"level" 3
Inheritance
• Linkage provides simple
inheritance.
new Object()
{}
object(Object.prototype)
delete myObject[name];
Arrays
• Array inherits from Object.
array.splice(number, 1)
delete myArray[1];
myArray.splice(1, 1);
• It is a source of enormous
expressive power.
function foo() {}
expands to
• this is bound at
the new
invocation time. constructor
object
arguments
• When a function is invoked, in addition
to its parameters, it also gets a special
parameter called arguments.
• It is an array-like object.
String.prototype.trim = function () {
return this.replace(
/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};
supplant
var template = '<table border="{border}">' +
'<tr><th>Last</th><td>{last}</td></tr>' +
'<tr><th>First</th><td>{first}</td></tr>' +
'</table>';
var data = {
first: "Carl",
last: "Hollywood",
border: 2
};
mydiv.innerHTML = template.supplant(data);
supplant
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' ?
r : a;
}
);
};
typeof
• The typeof prefix operator returns
a string identifying the type of a
value. type typeof
object 'object'
function 'function'
array 'object'
number 'number'
string 'string'
boolean 'boolean'
null 'object'
undefined 'undefined'
eval
eval(string)
/\/(\\[^\x00-\x1f]|\[(\\[^\x00-\x1f]|[^\x00-
\x1f\\\/])*\]|[^\x00-\x1f\\\/\[])+\/[gim]*/
• Yahoo!Widgets
• Embedded
ActionScript
• Empty strings are truthy
• keywords are case insensitive
• No Unicode support
• No RegExp
• No try
• No statement labels
• || and && return booleans
• separate operators for strings and
numbers
E4X
• Extensions to ECMAScript for XML
• Proposed by BEA
• Allows <XML> literals
• Not compatible with ECMAScript
Third Edition
• Not widely accepted yet
• Not in IE7
ECMAScript Fourth Edition
• A very large set of new features
are being considered.
• Good: [1, 2, 3]
• Bad: [1, 2, 3,]
Required Blocks
• Good:
if (a) {
b();
}
• Bad:
if (a) b();
Forbidden Blocks
• Blocks do not have scope in JavaScript.
• Good:
foo();
• Bad:
foo && foo();
switch Statement
• Avoid using fallthrough.
http://www.JSLint.com/
UHOH!
crock@yahoo-inc.com
produce.yahoo.com/crock/javascript.ppt