javascript (js) 3.pdffull stack javascript (หร อ isomorphic javascript) • ในบทน...
Post on 15-Sep-2020
24 Views
Preview:
TRANSCRIPT
Theerayut Thongkrau
JavaScript (JS)
Chapter 3
JavaScript (JS)• ภาษาโปรแกรมส าหรบพฒนา Web Application ทสามารถประมวลผลบน
Browser หรอบน Server กได • ใชพฒนาไดทงสวน frontend และ backend ซงระบบทพฒนาแบบนเรยกวา
Full Stack JavaScript (หรอ Isomorphic JavaScript)• ในบทนจะกลาวเฉพาะ JavaScript ทประมวลผลบน Browser เพอเพม
Logic เขาไปบนหนาเวบตามเหตการณตางๆ เชน– ขณะโหลดหนาเวบเสรจแลว– ขณะคลกทปม– กรอกขอมลในฟอรมชองนนเสรจแลว ตองการตรวจสอบบางอยาง
2
ความเปนมาของ JavaScript• พ.ศ. 2538 วศวกรบรษท Netscape สรางภาษา LiveScript เพอใชกบ Browser ชอ
Netscape Navigator• พ.ศ. 2539 ไดถกเผยแพรดวยชอ JavaScript เพอใหมความคลายคลงกบภาษา Java ท
ก าลงเปนทนยมในขณะนน• Netscape สง JavaScript ใหองคกร Ecma International เปนผก าหนดมาตรฐาน โดยตง
ชออยางเปนทางการวาภาษา ECMAScript รน 1 หรอ ES1 ในป พ.ศ. 2540• ถกพฒนาเรอย ๆ มาถง ECMAScript รน 5 หรอ ES5 ในป พ.ศ. 2552 ซงเปนทนยมใช
อยางแพรหลายจนถงปจจบน• ป พ.ศ 2558 ออก ES6 ชอเตมวา ECMAScript 2015 ชอเลน ECMAScript Harmony
หรอ ES6 Harmony• ป พ.ศ. 2559 - 2562 ออก ES ทกป จนถงปจจบน ลาสดคอ ES9
3
การแทรกค าสง JavaScript บนเวบเพจ• Internal Script - แทรกค าสง JavaScript ในแทก <script> ภายใตแทก
<head> เมอตองการใหโหลด หรอท างานกอนการแสดงผล หรอภายใตแทก<body> เมอตองการใหท างานในชวงแสดงผล
• External Script - น าค าสง JavaScript ในไฟลแยกตางหาก แลวอางถงไฟลในแทก <script> ซงอยภายใตแทก <head> เหมาะกบการแชรค าสงหรอฟงกชนใหกบเวบหลายหนา
4
Internal Script<!doctype html>
<html>
<head>
</head>
<body>
<h1>Hello JavaScript</h1>
</body>
</html>
5
เพมค าสง JavaScript ในการแสดงขอความออกทาง Console
<script>
console.log('Hello World')
console.log('Hi Pocky!')
</script>
ผลลพธ
กดป ม F12 และเลอกทแทบ Console
External Script
6
<script src="myscript.js"></script>
myscript.js
console.log('Hello World')
console.log('Hi Pocky!')
// ไมตองใสแทก HTML ใดๆในน
<!doctype html>
<html>
<head>
</head>
<body>
<h1>Hello JavaScript</h1>
</body>
</html>
อางองโดยใช Relative URL
ตองมแทกปดเสมอ
External และ Internal Script
7
html
head
<script>
statement
</script>
body
<script>
statement
</script>
<script src="mycode.js">
</script>
แทรกไวในสวนของ <head>Script จะท างานกอนทจะแสดงหนาเวบ
แยกเปนไฟลตางหาก ทมนามสกล .jsแลวอางองโดย Relative Path
แทรกไวในสวน <body> จะท างานขณะทแสดงหนาเวบท าตามล าดบจากบนลงลาง
JavaScript Comment• การอธบายโปรแกรมใชรปแบบเดยวกบภาษาซ
8
<html><head><script>
// แบบอธบายจบภายในบรรทดเดยว
/* แบบอธบายหลายๆ บรรทด บรรทดท 2บรรทดท 3 */
</script></head><body>
...</body></html>
การแสดงขอความแบบ Alert
9
<html>
<body><script>
alert('Hello JavaScript!')</script>
</body>
</html>
การด Error จาก Console• บน Google Chrome กด F12 และเลอกแทบ Console
10
เกด Error ทบรรทดท 6
• ชอตวแปรเปนแบบ case-sensitive• ตวแปรใน JavaScript ไมตองระบชนดของขอมล (Weakly Type) สามารถ
เปลยนแปลงชนดขอมลไดตลอดเวลา• การก าหนดคาใหตวแปรจะใชเครองหมาย =
let count = 2
let price = 53.50let name = 'Johny'let name2 = 'John'let isEmpty = false
การประกาศตวแปรแบบ let
11
ตวแปรชนด integer
ตวแปรชนด floating point
ตวแปรชนด string (JavaScript ไมมชนด char) และString กไมไดหมายถง Array ของ Character
ตวแปรชนด boolean ม 2 คา คอ true หรอ false
การประกาศตวแปรแบบ const และ let• ตวแปรทประกาศแบบ const จะไมสามารถก าหนดคาใหมได แตตวแปรแบบ let จะก าหนดคาใหมได
12
<html><head><script>
const a = 15a = 69console.log(a)
</script></head></html>
<html><head><script>
let a = 15console.log(a)a = 7console.log(a)
</script></head></html>
Reserved word
13
abstract delete goto null throws
as do if package transient
boolean double implements private true
break else import protected try
byte enum in public typeof
case export instanceof return use
catch extends int short var
char false interface static void
class final is super volatile
continue finally long switch while
const float namespace synchronized
debugger for native this with
default function new throw
Undefined และ Null
14
<html><body><script>
let personlet car = 'Volvo'console.log(person)console.log(car)
let car = nullconsole.log(car)
</script></body></html>
ตวแปรทยงไมมการก าหนดคา จะแสดงเปน Undefined
การก าหนดคาวางใหกบตวแปรจะใช null
ผลลพธทาง console
NaN (Not-A-Number) และ Infinity
15
<html><body><script>
let x = 'Joey' * 10 // NaNlet y = 10 / 0 // Infinityconsole.log(x)console.log(y)
</script></body></html>
ผลลพธทาง console
ตวแปรชนด Array
16
<html><head>
<script>let age = new Array()age[0] = 10age[1] = 20age[2] = 30console.log(age.length) // การขอจ านวนสมาชกของอาเรยconsole.log(age) // การขอขอมลทงหมดในอาเรยconsole.log(age[1]) // การเขาถงขอมลสมาชกแตละตว
let cars = []cars[0] = 'Ford'cars[1] = 'Volvo'cars[2] = 'BMW'console.log(cars[0])
</script></head></html>
การประกาศตวแปรอารเรยใหม
การก าหนดคาใหสมาชกแตละตว
การประกาศตวแปรอารเรยใหม
การก าหนดคาใหสมาชกแตละตว
ผลลพธทาง console
ประกาศ Array พรอมก าหนดคาเบองตน
17
<!DOCTYPE html><html><head>
<script>let age = new Array(10, 20, 30, 40, 50)console.log(age)console.log(age[3])
let score = [2, 4.5, 'three', 'two']console.log(score[0]) console.log(score['0'])
</script></head><body></body></html>
ผลลพธทาง console
ก าหนดคาเรมตนใหอาเรย 5 คา
ก าหนดคาเรมตนใหอาเรย 4 คาสามารถมสมาชกทมชนดขอมลแตกตางกนได
คนสมาชกดวย comma
ตวแปรชนด Object
18
<html><head><script>
let person = {id: 69,fullname: 'John Smith',weight: 72.5,option: ['move', 'stop', 'slow']
}
console.log(person.weight) // เขาถง property weightconsole.log(person.option[2]) // เขาถง property option
person.fullname = 'Robert Smith' // ก าหนดคาใหมconsole.log(person.fullname)
</script></head></html>
ผลลพธทาง console
อารเรยซอนใน object
การสราง object โดยขนตนดวย { และลงทายดวย }
รปแบบ property คนดวย : ตามดวย value
คนสมาชกดวย comma
Array ของ Object
19
<html><head><script>
let student = [ // ประกาศตวแปรอารเรย{ // สราง object แรก
id: 62001,fullname: 'ธจง'
},{ // สราง object ทสอง
id: 62002,fullname: 'โตยจง'
}
]
console.log(student[0].fullname) // เขาถง object แรก property fullnameconsole.log(student[1].id) // เขาถง object ทสอง property id
student[1].fullname = 'พโตย' // ก าหนดคาใหมconsole.log(student[1].fullname)
</script></head></html>
ผลลพธทาง console
ตวด าเนนการ (Operator)
20
Operator ค าอธบาย ตวอยาง คา x คา y
+ การบวก x=y+2 7 5
- การลบ x=y-2 3 5
* การคณ x=y*2 10 5
/ การหาร x=y/2 2.5 5
% การหารเอาเศษ (Modulo) x=y%2 1 5
** ยกก าลง x = y**2 25 5
++ เพมคาหนงคาใหกบตวแปรx=++y 6 6
x=y++ 5 6
-- ลดคาหนงคาใหกบตวแปรx=--y 4 4
x=y-- 5 4
ก าหนดคาเรมตนให y=5
การใช + กบ String• การตอ String
• ใช + ระหวาง String และตวเลข
21
txt1 = 'What a very'txt2 = 'nice day'txt3 = txt1 + txt2console.log(txt3)
What a verynice day What a very nice day
x = 5 + 5 // 10
y = '5' + 5 // 55
z = 'Hello' + 5 // Hello5
หรอ
txt1 = 'What a very'txt2 = 'nice day'txt3 = txt1 + ' ' + txt2console.log(txt3)
ตวด าเนนการก าหนดคา (Assignment Operators)
Operator ตวอยาง เขยนแบบเตม ผลลพธ
= x = y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0
22
ก าหนดคาเรมตนให x=10 และ y=5
ตวด าเนนการเปรยบเทยบ (Comparison Operators)
Operator ค าอธบาย Comparing ผลลพธ
== เทากน x==8 false
x==5 true
=== เทากนทงคา และชนดขอมล(exactly equal to)
x==='5' false
x===5 true
!= ไมเทากน x!=8 true
!== ไมเทากน คาตางกน หรอ ชนดขอมลตางกน
x!=='5' true
x!==5 false
> มากกวา x>8 false
< นอยกวา x<8 true
>= มากกวาเทากบ x>=8 false
<= นอยกวาเทากบ x<=8 true23
ก าหนดคาเรมตนให x=5
ตวด าเนนการตรรกะ (Logical Operators)
24
Operator ความหมาย ตวอยาง
&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true
ก าหนดคาเรมตนให x=6 และ y=3
ค าสงเงอนไข if
25
if (condition){
statement
}
<html><body><script>
let price = 1500if (price > 1000) {
console.log('Expensive')}
</script></body></html>
ผลลพธทาง console
ค าสงเงอนไข if…else
26
if (condition){
statement1
} else {
statement2
}
<html><body><script>
let price = 1500if (price > 1000) {
console.log('Expensive')} else {
console.log('Cheap')}
</script></body></html>
ตวอยาง
27
<html><body><script>
let r = confirm('Press a button!')if (r == true)
console.log('OK')else
console.log('cancel')</script></body></html>
การใชกลองยนยน (Confirm Box) จะ return คาtrue เมอผใชกด OK, false เมอผใชกด Cancel
เงอนไข if…else แบบยอ
28
<html><body><script>
let age = 15let level = (age<18) ? 'Young' : 'Old'console.log(level)
</script></body></html>
ค าสงเงอนไข if…else if…
29
if (condition 1){
statement1
} else if (condition 2){
statement2
} else if (condition n){
statement3
} else {
other_statement
}
<html><body><script>
let score = 65if (score >= 80)
console.log('A')else if (score >= 70)
console.log('B')else if (score >= 60)
console.log('C')else if (score >= 50)
console.log('D')else
console.log('F')</script></body></html>
ค าสงเงอนไข switch-case
30
switch (ตวแปรชนดใดกได){
case <ตวเลข,String>:statement
break
case <ตวเลข,String>:statement
break
…
default:
statement
}
ค าสง break
Colon
<html><body><script>
let test = 'male'switch (test) {case 1: console.log('Number!!')break
case 3.14:console.log('Floating Point!!')break
case 'male':console.log('String!!')break
case 'female':console.log('String!!')break
default:console.log('Other!!')
}</script></body></html>
ค าสงวนซ า while
31
while (condition){
statement
}
<html><head>
<script>
let cars = [ 'Ferrari', 'Benz', 'BMW', 'Mazda', 'Toyota', 'Honda' ]
let i = 0, length = cars.length
while (i < length) {
console.log(cars[i])
i++
}
</script>
</head></html>
ผลลพธทาง console
ค าสงวนซ า for
32
for (ก ำหนดคำเรมตน; เงอนไข; ค ำสงเพม/ลดคำ){
statement
}
<html><head><script>
let cars =['Ferrari','Benz','BMW','Mazda','Toyota','Honda']
for (i = 0; i<cars.length; i++) {console.log(cars[i])
}</script></head></html>
หรอfor (ตวแปรควบคม in ชออำรเรย){
statement
}
<html><head><script>
let cars =['Ferrari','Benz','BMW','Mazda','Toyota','Honda']
for(let i in cars){console.log(cars[i])
}</script></head></html>
ผลลพธทาง console
การสรางฟงกชน<html><head><script>
function ชอฟงกชน(พารามเตอร1, พารามเตอร2, พารามเตอรN, ...) {ชดค าสงตางๆreturn [ชอตวแปรทสงกลบ]
}</script></head>
<body>...
</body></html>
33
ฟงกชนตวแปรรบเขา คาสงกลบ
ฟงกชนควรเขยนในสวน <head> เสมอ
การเรยกใชฟงกชน
34
<html><head><script>
function myFunction() {…
}
myFunction() //เรยกใชฟงกชน</script></head><body>
Hello world<script>
myFunction() //เรยกใชฟงกชน</script>
</body></html>
เรยกใชเมอโหลดเวบ เรยกใชตามเหตการณ<html><head><script>
function myFunction() {…
}</script></head><body>
Hello world<!-- เรยกใชฟงกชนในเหตการณตางๆ --><a href="#" onclick="myFunction()">Execute</a><input type="button" onclick="myFunction()" value="Click"><h2 onmouseover="myFunction()">Hello</h2>
</body></html>
การเรยกใชฟงกชน จะใชชอฟงกชนทนยามตามดวยวงเลบ ( )สามารถใสคา หรอตวแปรทจะสงใหในวงเลบ คนดวย comma
ฟงกชนรปแบบตางๆ
35
helloแบบไมรบและไมสงกลบขอมล
printGreetingnameแบบรบขอมล แตไมสงขอมลกลบ
findAverage
num1num2num3
คาเฉลยแบบรบและสงกลบขอมล
<html><head><script>
let address = 'Bangkok' // ตวแปรชนด Global
function hello() { // ไมมการรบขอมลconsole.log('You are from ' + address)
}
hello() // เรยกใชฟงกชน hello() กอนโหลดหนาเวบ</script></head>
<body><input type="button" onclick="hello()" value="Click">
</body></html>
แบบไมรบและไมสงกลบขอมล
36
เรยกใชฟงกชน hello( ) เมอเกดเหตการณคลก
กอนคลกทปม
หลงคลกทปม
<html><head><script>
function printGreeting(name) {console.log('Hello ' + name)
}</script></head><body>
<a href="#" onclick="printGreeting('Tee')">Run JavaScript Code
</a></body></html>
แบบรบขอมล แตไมสงขอมลกลบ
37
รบขอมลเขา
เรยกใชฟงกชน
สงขอมลไปยงฟงกชน
แบบรบและสงกลบขอมล
38
findAverage<html>
<head>
<script>
function findAverage(num1, num2, num3) {
let sum = num1 + num2 + num3
let avg = sum/3
return avg
}
let ans = findAverage(3, 7, 6)
alert(ans)
</script>
</head>
<body></body></html>
รบขอมลเขา (parameter)
เรยกใชฟงกชนสงขอมลไปยงฟงกชน (argument)
num1num2num3
คาเฉลย
ขอมลทสงกลบ
กจกรรม• จงสรางฟงกชนทมรปแบบดงน
function findBMI(weight, height)
• เรยกใชฟงกชนทสรางขน โดยทดสอบสงคาใดๆไปยงฟงกชน
39
การสรางฟงกชนเกบในตวแปร• ฟงกชนใน JavaScript สามารถนยาม และเกบไวในตวแปรได ซงจะเปนฟงกชนทไมมชอ (Anonymous Function)
40
<html><head><script>let p = function(a, b) {
return a + b}
</script></head><body><script>let result = p(8, 9)console.log(result)
</script></body></html>
เกบฟงกชนไวในตวแปร p
เรยกฟงกชนผานชอตวแปร p พรอมกบสง argument
การสรางฟงกชนเกบใน object• ฟงกชนใน JavaScript สามารถนยาม และเกบไวในตวแปรชนด object ได และสามารถเรยกใชได ผานชอ object
41
<html><head><script>let t = { id:69, fname:'Tee', lname:'Jung', say: function(name) { return 'Hello ' + name }
}console.log( t.id + ' ' + t.fname + ' ' + t.lname )console.log( t.say('John') )
</script></head><body></body></html>
เกบฟงกชนไวใน key ชอ say
เรยกฟงกชนผานชอ object พรอมกบสง argument
Built-in Object• Built-in Object คอ object มาตรฐานในภาษา JavaScript ภายใน
ประกอบดวย – Property ใชในการก าหนดหรอขอคาคณสมบตของ built-in object
รปแบบการเรยกใช
[ชอ Object].[ชอ property]– Method คอ ฟงกชน หรอชดค าสงพรอมใชส าหรบท างานกบ built-in
object นนรปแบบการเรยกใช
[ชอ Object].[ชอฟงกชน] (รายการ argument)42
ตวอยาง Built-in Object• Number - parseInt(), parseFloat(), isNaN(), isInteger()• Math - cos(), exp(), log(), max(), min(), sqrt()• String - search(), substr(), replace()• Date - getDate(), getHours(), getMinutes()• Array ประกอบดวย property เชน length ใชในการขอจ านวนชองของ Array
43
ดรายการ Built-in Object พรอมตวอยางการใชไดทhttp://devdocs.io/javascript
กจกรรม• ศกษา built-in object ชอ Date จาก http://devdocs.io/javascript/
แลวเรยกฟงกชนพรอมใช เพอแสดงวนท และเวลาปจจบนออกทาง Console
44
<html><body><script>
let d = new Date()_________________________________________
_________________________________________
_________________________________________</script></body></html>
Math Object
45
<html><body>
<script>let a = Math.min(5, 10, 8, 7, 2, 6)console.log(a)
</script>
</body></html>
String Object
46
<html><body><script>
let str = 'Hello World'
for (i=0; i<str.length; i++) {console.log(str.charAt(i))
}
</script></body></html>
Property length ของ String Object ใชเปนเงอนไขในลป
ฟงกชน charAt ของ String Objectใชขออกขระแตละตวภายใน String ม argument เปนต าแหนงอกขระ ซงเรมจากต าแหนงท 0
String Object
47
<html><body>
<script>let str = 'How are you doing today?'let result = str.split(' ')
for (i=0; i<result.length; i++) {console.log(result[i])
}</script>
</body></html>
เมธอด split ของ String Object ใชในการแยก String ทคนดวยขอความทก าหนด เชน จากตวอยางคอ แยกString ทงหมดทคนดวยชองวาง มการสงกลบเปน Array ของ String
String Object
48
<html><body>
<script>let str = 'เดกภาคคอม!'let n = str.search('คอม')console.log(n)
</script>
</body></html>
ฟงกชน search ของ String Object ใชคนหา String ม argument เปน String ทตองการคนหา และมการสงกลบเปนต าแหนงอกขระแรกทเจอ
JavaScript มองตวแปรตาง ๆ เปน Object ซงสามารถเขาถง method หรอ property ไดทนท
Window Object
49
Window Property
50
<html><head><script>
window.location = 'http://www.google.com/'</script>
</head><body></body></html>
ก าหนดคาใหมใหกบ property location จะเกดการสงตอ (Redirect) ไปยง URL ใหม
ฟงกชน open บน Window object
51
<html><head><script>function openPopup() {window.open('http://www.google.com', '', 'width=600,height=250')
}</script></head>
<body><input type="button" value="Open!!" onclick="openPopup()">
</body>
</html>
ใชเมธอด open ใน window object เพอเปดหนาเวบบนหนาตางใหม ตาม URL ทก าหนด
Window Method
52
<html><head><script>function openPopup() {let winObj = window.open('', '', 'width=300,height=150')winObj.document.write('<html><body><h1>Sample Text</h1></body>')
}</script></head><body><input type="button" value="Open!!" onclick="openPopup()">
</body></html>
ใชฟงกชน open ใน window object เพอเปดหนาเวบบนหนาตางใหม แลวน า object ของหนาตางนนไวในตวแปร winObj
เขาถง document object ซงอยภายใต window object และเรยกฟงกชน write เพอเขยนค าสง HTML ลงบนหนาตางใหม
top related