Title: JavaScript
1JavaScript
- ???
- http//www.ywdeng.idv.tw
2JavaScript ??
- Client-Side JavaScript (CSJS)
- Mozilla Foundation implementation of the
ECMAScript standatd - JavaScript is NOT Java
- Java ? JavaScript ???????,????????????????????????
- Netscape ????? LiveScript,??? Sun Microsystems
??,??? JavaScript
3JavaScript ??
- JavaScript???
- ???????????
- JavaScript???
- ?????, ????
- ???????????????, ??????????????
- ??????????, ???????
- ???????, ????????
4????
- Firefox???
- ???? http//www.mozilla.com/
- FirebugJavaScript ??????
- ? Firefox ???? ???
- ?? Firefox ??????https//addons.mozilla.org/ ??
firebug
5??Hello JavaScript
- ? document.write ?????? Hello JavaScript
- document ????HTML??
- write() ????????
- JavaScript ??????ltscript type"text/javascript"gt
lt/scriptgt????
6????
- Dynamically Typed ??????
- Interpreted ??,??????
- Functions as First-Class Objects ?????
7????
- Dynamically Typed ????
- Data types are NOT declared
- Data types are NOT known until execution time
- Data type is associated to the value of the
variable rather than the variable itself
var x 5 // set x to 5 (number) x "Hello!"
// set x to "Hello!" (String)
8????
- Interpreted ?????
- The code is stored as text and interpreted into
machine instructions and stored in memory as the
program runs. - Line by line ????????
9????
- ?? . ??? ???
- ???????(Property)
- ??????????(Method)
- ?????????? (Object)
- ??????.???? ???, ??????????, ?????????
- ??????.????(), ??????????,???????
10????
- ??????
- ?????? var ???????
- ?????? var ???? new Array(?????)
- ?????? (???????var)var ???? new ????
11????
- ????
- ?????? function ????(??1,??2)
- ???????????????, ????return(var)????????????
- Functions as First-Class Objects
- Function is a type of built-in object
- Functions are unique only by name, not by name
plus arguments
12????Functions as First-Class Objects
var newMethod new Function("alert('new
method')") newMethod() // alerts "new
method" function newMethod2() alert('new
method') newMethod2() // alerts "new method"
13????
- JavaScript ?????????
- ???????, ?????TAB??????? ????????????, ???C??
- ???????????????
- ??????????C????, ??????? \n
- / ???? /// ????
14????????JavaScript
- HTML??????????????
- ???????????HTML???, ???????????JavaScript???ltfont
size"4" onMouseover'color"ff00ff"'gttest1lt/fon
tgt - ???????JavaScript??????ltscriptgt
lt/scriptgt????ltscriptgt??????HTML???????,
??????????????????? - ???????JavaScript?????.js???, ???ltscriptgt?src????.
js?????, ????HTML??? - ??????????????HTML??????, ????????id???(??)
15JavaScript??????
- ??HTML??(??)????????
- ltfont size"4" onclick 'color"ff00ff"'gt
test1lt/fontgt - ltfont size"4" onclick change()gt
test1lt/fontgt - ?JS??????????
- ltscript LANGUAGE"javascript"gt
- document.onclick change
- function change()
- document.getElementById("a").color
"ff00ff" -
- lt/scriptgt
- ltfont id"a" size"4"gt test1lt/fontgt
16??????
- Primitive Data Types
- boolean ?/?
- number ??(????)
- string ??
- Special values
- undefined ???
- null ??
17??????
- booleans ??,?/???/?
- Possible values
- true
- false
- 1 ??? true
- 0 ??? false
var x false var y true var z 1 alert (y
z) // alerts 'true'
18??????
- Numbers ??
- 64???
- Similar to double in Java
- ???????
- ??? 32-bit ??(?????),??????? 64-bit number
var x 6 // x 64-bit var y x ltlt 2 // x
32-bit, y 64-bit
19???????????
- ? document.write ??? 1 ? 10 ???
- ??
- while (??)
- for (?? ?? ??)
20????????????
- ? document.write ??? 1 ?? 10 ???
- ????
- if (??)
- if (??) else
- if ((??1) (??2))
- if ((??1) (??2))
21Special Number Values
22??????
- Strings ??
- A string is a sequence of zero or more Unicode
values used to represent text. - Strings are immutable
- Modification produces a new string
- JavaScript ????,??????
- ?????????
23Special Characters ????
24???????
- ? document.write ???????
- ????ltpregt???? \t ??
- ????lttablegt??
- ???? bgcolor ????????????
- ???? CSS ? trhover ????????????
25?? Objects
- ?? boolean, number, string ?? Primitive Data Type
??,????????? - Function
- Date
- Document Object Model (DOM) elements
var myCar new Object() // the built-in Object
type var myCar2 // the object literal
26?? Objects
- Object properties are stored using an associative
array
27Using a for in loop
28Object Functions
29Object Literal Notation
30Expando Properties
myCar.print null delete myCar.print
31Primitive Data Type Wrapper Objects ????
- Boolean, Number, String
- Primitive data types just store data and dont
have any methods or properties - JavaScript silently converts the primitive data
types to and from the wrapper objects so that we
can use methods without having to cast to another
object first
32instanceof
- instanceof determines whether an object derives
from a particular type
33The constructor Property
- ??,? new ???
- The constructor property references the function
that created an object - can be used to determine an objects type
34?? ???
- Equality ??
- Equal
- ?????
- Not equal !
- ??????
- Strict equal
- compare both the value and type of the operands
- ???????????
- Strict not equal !
35Variables and Function Arguments
- ???????? function() ?
- Only the global object (the window object in
browsers) and functions are variable scope
boundaries - Other blocks, such as if-then-else statements and
while loops, dont provide a variable scope
boundary. - Variables declared inside a block other than the
function block will be accessible outside that
block
36Function-Level Variable Scope
37Globally Scoped Variables
- The global window is the root of the DOM and is
accessed through the window keyword
38??
- ????
- ????? x ? y,????? z x y
- ??
- ltinput type"text" id"x" /gt ??????
- ltinput type"button" onclick"doIt()" value"??"
/gt ????,???? - document.getElementById("x").value ?????????
- m parseInt(x) ????????(???)
39Undeclared Variables
40Null(?) and undefined(???)
- null is a reserved word that means no value and
is used to point a variable to no data so that
memory can be reused - undefined is the default value of a newly
declared variable - undefined is a primitive value and a type
41Comparing null and the undefined Value
42Comparing null to Itself
- Comparing a null valued variable and an undefined
valued variable will evaluate to true when using
the nonstrict comparison and evaluate to false
when using the strict comparison
?? null,???? null
43Comparing Using the undefined Type
typeof(x) ??? undefined alert(typeof(x)
undefined) // alerts false
44typeof ????
- typeof returns a string based on the data type of
its operand
45typeof Evaluations
46Function Arguments ??
- Method arguments are always supplied to the
function in a special local arguments variable - Local variable is accessible once inside the
function through the arguments keyword
47Implicit Arguments
48Explicit Arguments
49Undefined Arguments
50Dynamic Arguments
51callee ????
- The callee property available on a functions
local arguments variable accesses the function
being executed - using arguments.callee to access the sayHello
method
52Recursive Anonymous Methods with arguments.callee
53??
- ?? N ??,?????????
- ??
- 5! 1 2 3 4 5 120
- ??
- ? ltdiv id"z" /gt ??????
- ? document.getElementById("z").innerHTML ?? div
?? HTML ??
54this
- this in JavaScript points to the current owner of
the executing method - can point to
- the global window object if the executing method
is procedural, - a DOM element if the executing method is handling
a DOM event, or - an object if the executing method is contained
within the objects definition
55The Different Uses of this
56Error Handling
- Try-Catch-Finally Mechanism
- Code wrapped in a try block that causes an error
to be thrown transfers control to the catch
block, which receives as a parameter an instance
of the built-in Error type describing the error
that occurred
57Standard Error Properties
- The catch block accepts a single parameter, e,
which is an instance of the Error type. The Error
type has two standard properties
58Nonstandard Error Properties
59Throwing an Error
60Using the finally Block
- the finally block always executes after either
the try block or the catch block execution is
complete
61Using the finally Block
62Unhandled Exceptions
- The other error handling mechanism is the global
error event attached to the window, which can be
used as a catchall for unhandled errors
63The Error Event Handler
- The signature for the error handler function
takes three parameters the error message, the
URL of the page where the error occurred, and the
line number of where the error occurred
64Globally Handling an Error
65Delayed Code Execution Using Timeouts and
Intervals
- Timeouts execute only after the delay expires
- Intervals execute when the time delay expires and
then reset themselves so that they will
continually execute after the delay expires
66Timeouts
- Creating a timeout is done through the
window.setTimeout method - the amount of the delay is in milliseconds
- Use window.clearTimeout method to un-register
timeout
67Explicit Anonymous Function
68Problems with Functions and Variables
69Inducing Scope for Our Predefined Function
70Intervals
- Intervals are identical to timeouts except that
the function or string expression is continuously
evaluated at the specified interval until the
interval is canceled, instead of executing only
one time when the delay expires - using a window.setInterval method
71Using an Interval
72Clearing an Interval
73?????
- ????????????
- ????????
- ltbody onload"showClock()"gt
- d document.getElementById("clock")
- ltdiv id"clock" align"right"gtlt/divgt
- d. innerHTML
74??????
- ????????
- ?????????????,????????????
75???????
76JavaScript????
- ????window ????????
- ???? ????, ??JS?????????????
- Array, Boolean, Date, Error, Function, Global,
Math, Number, Object, RegExp, String - ???? ?????????, ?????????????????
- location, navigator, history, screen
- ???? ??Html??, ???document????????????
77JavaScript????
?? ?? ?? ??
length ?????? closed ????????(True/False)
name ????? defaultStatus ?????????
status ???????? screenLeft ????????X???(For IE)
opener ?????????? screenTop ????????Y???(For IE)
parent ????? screenX ????????X???(For NS)
top ?????? screenY ????????Y???(For NS)
window ?self pageXOffset ????????X???(For NS)
self window???? pageYOffset ????????Y???(For NS)
78JavaScript???? (?)
?? ?? ?? ??
moveBy(x, y) ????x, y??? moveTo(x, y) ????(x, y)???
resizeBy(x, y) ??????x, y??? resizeTo(x, y) ?????x, y??
scrollBy(x, y) ??????x, y??? scrollTo(x, y) ??????????????x, y???
prompt(msg, input) ????????msg, input???? confirm(msg) ????????msg ???True/False
alert(msg) ????????msg close() ????
setTimeOut (exp, time) ???????time?????(?????)?????exp???? setInterval (exp, time) ???????time?????(?????)?????exp????
clearTimeOut() ??setTimeOut???? clearInterval() ??setInterval????
open(url, name, features) ??url??,??? name,?????feature??? print() ????
79JavaScript???? (?)
- ??????(??window.open()??)??????????
?? ?? ?? ??
copyhistory ????????(0 or 1) toolbar ???????
directories ??????? scrollbars ??????
fullscreen ??????? resizable ??????????
location ??????? height ????
menubar ???????? width ????
status ???????
80JavaScript???? (?)
- location?? ????????????????(URL)
?? ?? ?? ??
hash URL??????? pathname URL?????????
host URL??????????? hostname URL??????
port URL?????? protocol URL???????
href URL, ???????????????? search URL????????
?? ?? ?? ??
reload ?????? Replace(url) ????????url?????
81JavaScript???? (?)
- navigator?? ?????????? (??????)
?? ?? ?? ??
appCodeName ????????? cpuClass CPU??
appName ????? platform ??????
appMinorVersion ??????? plugins ????
systemLanguage ??????? userProfile ???
userLanguage ???????? userAgent HTTP??????
appVersion ???????????? onLine ?????????
82JavaScript???? (?)
- history?? ??????????
- window.history.back() ?????????
?? ??
length ??????
?? ??
back() ?????
forward() ?????
go(num) ?????(num lt 0)??????(num gt 0)
83JavaScript???? (?)
- screen?? ??????????
- var SH window.screen.height ???????????????SH??
?? ??
availHeight ??????? (??)
availWidth ??????? (??)
colorDepth ??????? (????????)
height ???????? (??)
width ???????? (??)
84JavaScript???? (?)
- document?? ?????????, ??lthtmlgt???????,??,???,??,?
?
?? ?? ?? ??
charset ???????(For IE) characterSet ???????(For NS)
cookie ?????Cookie height Html?????(For NS)
domain ????????? width Html?????(For NS)
referer ???Html?URL lastModified Html??????
url Html???URL Title ?????????
85JavaScript???? (?)
?? ?? ?? ??
close() ?? Html?? getElementById(i) ?????ID???????i???
open(type) ??type???MINE???????????(?????) getElementByName(n) ?????Name???????n???
writeln(data) ?data??????????????? getElementByTagName(t) ?????????????t???
write(data) ?data????????
86JavaScript???? (?)
?? ?? ?? ??
all ??????? anchors ???name???ltAgt??
forms ??????? links ???href???ltAgt??
images ??????? styleSheets ????????
applets, embeds, plugins applets, embeds, plugins ??Java Applets, ????????? ??Java Applets, ?????????
87JavaScript???? (?)
- ????, document???????body, ???????
- document.body.bgColor Blue ????????????????
?? ??
link ??ltbodygt???LINK??, ???????????????
alink ??ltbodygt???ALINK??, ??????????????
vlink ??ltbodygt???VLINK??, ??????????????
background ??ltbodygt???BACKGROUND??, ????????
bgColor ??ltbodygt???BGCOLOR??, ????????
text ??ltbodygt???TEXT??, ?????????
88JavaScript????
?? ?? ?? ??
onLoad ??????????? onKeyPress ????????????
onUnload ?????? onKeyDown ?????????
onClick ?????????? onKeyUp ?????????
onDbclick ??????????? onSubmit ?????
onMouseDown ??????????? OnReset ???????
onMouseUp ??????????? onSelect ??????????
onMouseOver ??????? onChange ??????????
onMouseMove ????????? onMove ????????
onMouseOut ??????? onResize ??????????
onFocus ???????? onAbort ??????????
onBlur ??????? onError ???????