Post on 18-Jul-2015
Javascript forPHP Developer
Đặng Minh Tuấn - hoctudau.comPHP Day 2012
HOCTUDAU.COM DANG MINH TUAN
About Me
Đặng Minh Tuấn● www.ddth.com/member.php/51960-zmt264● linkhay.com/u/ohisee● www.facebook.com/dangminhtuan● www.youtube.com/hoctudau● hoctudau.com
Kinh nghiệm:● 2006: FrontEnd Engineer tại World Ideas● 2008: Project Manager kiêm Tech Lead tại NAISCORP (socbay.com)
Diễn giả PHP Day nhiều năm:● 2008 = HTML, CSS, JS Best Practices● 2009 = HTML, CSS Trends● 2010 = HTML5, CSS3, JS● 2012 += Power your PHP Skill (by learning HTML, CSS, JS :D)
HOCTUDAU.COM DANG MINH TUAN
Quy ước:
Chữ cái● JS = Javascript● dev = developer● app = application● hoctudau = tên biến, hàm ngẫu nhiên● hoc tu dau = chuỗi ngẫu nhiênPhát âm: Anh hay Việt?● PHP● echo
HOCTUDAU.COM DANG MINH TUAN
Quy ước: mầu nền
PHP và JS giống nhau: Nền trắng, chữ đen
HOCTUDAU.COM DANG MINH TUAN
Quy ước: mầu nền
PHP và JS khác nhau: nền đen, chữ trắng
HOCTUDAU.COM DANG MINH TUAN
Phần 1: Vai trò của JStrong thế giới web hiện đại
HOCTUDAU.COM DANG MINH TUAN
Cơ duyên nào đưa bạn đến với PHP?
● Đầu tiên là học làm web tĩnh: HTML, CSS trước.
● Một số người biết JS trước cả PHP● Sự thực: một số lập trình PHP không giỏi
HTML, CSS, JS nhưng đa số đều biết HTML, CSS, JS ở mức độ nào đó. Hiếm ai (tôi chưa gặp ai) chỉ biết mỗi PHP!
HOCTUDAU.COM DANG MINH TUAN
Tại sao lập trình viên PHP nên học (và giỏi) Javascript
● Trong quá khứ xa: ứng dụng web tập trung vào server-side hơn.
● Thời gian gần đây: client side trở nên phức tạp hơn và thực hiện nhiều nhiệm vụ hơn (richer). Web apps cân bằng hơn giữa client side và server side (thậm chí là client side nhỉnh hơn).
● HTML, CSS, JS làm được nhiều thứ!!!.● Học không có nghĩa là "copy & paste", hoặc
biết dùng "tool sinh code" => học như bạn đã học PHP
JS làm được gì?
Tạo ứng dụng mobile bằng HTML, CSS, JS với các Web RunTime platforms (WRTs)● iPhone — Titanium Mobile, PhoneGap● Android — Titanium Mobile, PhoneGap)● Palm webOS — Mojo● Sony Ericsson — Sony Ericsson WebSDK
(PhoneGap)● Nokia — Nokia WRT● Blackberry — PhoneGap
HOCTUDAU.COM DANG MINH TUAN
JS làm được gì?
Và nhiều thứ khác● Brower Extensions: Firefox Addons, Google
Chrome Extensions ...● Desktop Application: Windows 8 Apps,
Google Chrome Package Apps, ...● Google Script (Google Forms,
Spreadsheet...): Enterprise Apps● Web Games, Web Apps● Server side: Node.js
HOCTUDAU.COM DANG MINH TUAN
Cần học những gì của JS?
Không chỉ đơn giản là "tooltip", "menu", "chuyển động". Mà còn là:● Quản lý và thực thi những hành vi người
dùng phức tạp ở giao diện người dùng (UI).● Tương tác với API ở client: DOM, local
storage ...● Kể cả học các Framework như jQuery thì
cũng cần nắm vững căn bản về JS (sẽ liệt kê kiến thức ở phần cuối bài thuyết trình) vì làm jQuery cũng vẫn dùng cái đó.
HOCTUDAU.COM DANG MINH TUAN
Tin tốt
● Javascript có cú pháp C-Like (NHƯ PHP). Nếu bạn thực hiện những toán đơn giản: cộng, trừ, tính số PI, tính sin... thì có thể code hoàn toàn như PHP.
● Việc học tập giúp bạn trở nên thông minh hơn, học nhanh hơn, đáp ứng được nhiều yêu cầu (tuyển dụng, của khách...) hơn.
● Bây giờ có nhiều JS Frameworks rất tốt: jQuery,...
● Cộng đồng JS dev: đa dạng, sáng tạo, đông đảo
HOCTUDAU.COM DANG MINH TUAN
Tin xấu
Vài thứ khá khác biệt● Object Model dễ gây hiểu lầm● Scope rất khác biệt● Khả năng tùy biến: rất quái dị● và nhiều khác biệt khác
HOCTUDAU.COM DANG MINH TUAN
Học ở đâu và như thế nào?
Rất nhiều link, sách lởm: lạc hậu hoặc tập trung vào các "công thức".Vài nguồn đáng tham khảo:● Mozilla’s Core JavaScript Guide● Mozilla’s Core JavaScript Reference● Eloquent JavaScript● JavaScript: The Definitive Guide
HOCTUDAU.COM DANG MINH TUAN
Phần 2: Vài kiến thức JS cơ bản
học nhanh JS trong 15 phút, dành cho những lập trình viên PHP chưa biết hoặc
chỉ biết một chút về JS
HOCTUDAU.COM DANG MINH TUAN
Chú ý
bạn là PHP developer, tức là coi như bạn đã biết kiến thức căn bản và tư duy lập trình:● bản chất của biến, đối tượng● các kiểu biến: số, chuỗi, mảng, lớp ...● phép gán, biểu thức, biểu thức chính quy ...● các phép toán, toán tử ...● lệnh điều kiện (rẽ nhánh): if, else, switch ...● vòng lặp: while, do, for ...● nguyên lý DRY
Đặt tên biến: Giống
$n = 1;$b = true;$s = "hoc tu dau";
$n = 1;$b = true;$s = "hoc tu dau";
HOCTUDAU.COM DANG MINH TUAN
Đặt tên biến: Khác
n = 1$ = 1;var n = 1;var x = 0, y = '';
$n = 1;
$x = 0; $y = '';
HOCTUDAU.COM DANG MINH TUAN
Khai báo biến: Mảng
var a = [1,2,3]; $a = array(1,2,3);
HOCTUDAU.COM DANG MINH TUAN
Khai báo biến: Mảng
$a = [1,2,3]; PHP 5.4$a = [1,2,3];
HOCTUDAU.COM DANG MINH TUAN
Khai báo biến: Mảng liên kết (assoc)
var o = {"one":1,"two":2
};
$o = array("one"=>1,"two"=>2);
PHP 5.4["one"=>1, "two"=>2]
Bản chất và Nhập dữ liệuJavascript: Chạy ở client-side<div id="x">5</div><input id="y"><script>a = document.getElementById("x");b = a.innerHTML;c = document.getElementById("y");d = c.value;
PHP: chạy ở server và lấy được dữ liệu gửi từ client-side lên<form>
<input name="y"><input type="submit">
</form><?php
$a = $_GET['y'];
HOCTUDAU.COM DANG MINH TUAN
Bản chất và Xuất dữ liệuJavascript: Chạy ở client-side<div id="x">5</div><input id="y"><script>a = document.getElementById("x");b = a.innerHTML;a.innerHTML = 2 * b;c = document.getElementById("y");d = c.value;c.value = 3 * d;
PHP: chạy ở server và gửi được dữ liệu xuống client-side<form>
<input name="y"><input type="submit">
</form><?php
$a = $_GET['y'];echo 2 * $a;
JS Hello World - Event-Driven Programming
Cú pháp
if (1===1) {...}switch, for, while, do-whilefor (var i=0, out=''; i<100; i++) {
out += i + ',';}funtion hoctudau(a,b=2) {
return a*b;}
if (1===1) {...}switch, for, while, do-whilefor ($i=0, $out=''; $i<100; $i++) {
$out .= $i . ',';}funtion hoctudau($a,$b=2) {
return $a*$b;}
Closures (Anonymous functions)
var hoctudau = function (a,b) {return a * b;
}hoctudau(3, 4); //12
PHP 5.3 (PHP 5.4 hỗ trợ $this)$hoctudau = function ($a,$b) {
return $a * $b;}$hoctudau(3, 4); //12
Function Scope: Phạm vi hàm $a = function () {
$c =3;$b = function ($a, $b) {
return $c * $a * $b;};return $b;
};$b = $a();alert($b(1, 2)); //6
$a = function () {$c =3;$b = function ($a, $b) {
return $c * $a * $b;};return $b;
};$b = $a();echo($b(1, 2)); //Notice: Undefined variable: c//0
Tạo và gọi hàm trong JS
Lưu ý: nếu muốn làm tốt hơn, nâng cao hơn thì nên tìm hiểu về Unobstrusive JS
Bắt lỗitry {
throw new Error('ouch');} catch (e) {
msg = e.message;}
try {throw new Exception('ouch');
} catch (Exception $e) {msg = $e -> getMessage();
}
HOCTUDAU.COM DANG MINH TUAN
Toán tử
nối chuỗi:x = 'hoc' + 'tu';x += 'dau'; //hoctudau
nối chuỗi:$x = 'hoc' . 'tu';$x .= 'dau'; //hoctudau
HOCTUDAU.COM DANG MINH TUAN
Constructors/Classes
var hoctudau = new OnlineCenter();
$hoctudau = new OnlineCenter();
HOCTUDAU.COM DANG MINH TUAN
ClassJS constructor functionfunction OnlineCenter(name) {
this.name = name;this.getName = function () {
return this.name;}
}var hoctudau = new OnlineCenter("HocTuDau");hoctudau.getName(); //HocTuDau
PHP Classclass OnlineCenter {
var $name; //PHP 4public $name; //PHP 5function __construct($name) {
$this->name = $name;}function getName() {
return $this->name;}
}$hoctudau = new OnlineCenter("HocTuDau");hoctudau->getName();//HocTuDau
ClassJS Prototypefunction OnlineCenter (name) {
this.name = name;}OnlineCenter.prototype.getName =function() {
return this.name;}var hoctudau = new OnlineCenter("HocTuDau");hoctudau.getName(); //HocTuDau
PHP Classclass OnlineCenter {
var $name; //PHP 4public $name; //PHP 5function __construct($name) {
$this->name = $name;}function getName() {
return $this->name;}
}$hoctudau = new OnlineCenter("HocTuDau");hoctudau->getName();//HocTuDau
ClassJS Object literalvar hoctudau = {
name: "HocTuDau",getName: function() {
return this.name;}
};hoctudau.getName(); //HocTuDau
PHP Literal$hoctudau = (object) array();$hoctudau->name = 'HocTudau';$hoctudau->getName = function() {
return $GLOBALS['hoctudau']->name;};
$method = $hoctudau->getName;echo $method();//HocTuDau
HOCTUDAU.COM DANG MINH TUAN
ClassJS Object literalvar hoctudau = {
name: "HocTuDau",getName: function() {
return this.name;}
};hoctudau.getName(); //HocTuDau
PHP (5.4) Literalhttps://github.com/aviat4ion/JSObject$hoctudau = new JSObject(
'name' => 'HocTuDau';'getName' => function() {
return $this->name;}
);
$hoctudau->getName();//HocTuDau
Funny JS operators
typeof● typeof 1; //number● typeof(1);instanceof● ([1,2]) instanceof Array; //true● ([1,2]) instanceof Object; //truedelete● var o = {a:1}; delete o.a; o.a;// undefined
HOCTUDAU.COM DANG MINH TUAN
9 global functions4 number-relatedparseInt()parseFloat()isNaN()isFinite()
4 to encode/decode URIsencodeURIComponent()decodeURIComponent()encodeURI()decodeURI()
eval()
4 number-relatedintval()floatval()is_nan()is_finite()
4 to encode/decode URIsurlencode()urldecode()????
eval()
9+ constructorsObject()Array()RegExp()Function()String()Number()Boolean()Error(), SyntaxError() ...Date()...
Literalsvar o = {};var a = [];var re = /[a-z]/gmi;var f = function(..) {...}function f(..) {...}var s = 'hoctudau';var n = 123;var b = true;
var o = new Object();var a = new Array();var re = new RegExp("[a-z]", "gmi");var f = new Function("..","...");
var s = new String('hoctudau');var n = new Number(123);var b = new Boolean(true);
Object.prototype
var o = {};o.toString(); // "[object Object]"o.valueOf() === o; //trueo.hasOwnProperty('toString'); //falseo.propertyIsEnumerable('toString'); //falseo.isPrototypeOf(Array); //falseo.constructor === Object; //true
Array.prototype
var a = [1,2,3,4];a.length; // 4a.push('hoc tu dau'); //[1,2,3,4,'hoc tu dau']a.pop(); //[1,2,3]a.unshift('hoc tu dau'); //['hoc tu dau',1,2,3,4]a.shift(); //[2,3,4]a = a.concat(5,6,'htd'); //[1,2,3,4,5,6,'htd']
HOCTUDAU.COM DANG MINH TUAN
Array.prototype
var a = [3,2,4,1,2];a.sort; //[1,2,2,3,4]a.indexOf(2); //1a.lastIndexOf(2); //4a.slice(1,3); //[2,4]a.splice(...); //remove and add item(s)a.reverse(); //[2,1,4,2,3]a.join(' > '); //"3 > 2 > 4 > 1 > 2" ~ implode()
HOCTUDAU.COM DANG MINH TUAN
RegExp.prototype
var re = /[a-z]/gmi;re.exec("hoc tu dau"); //"h" (returns matches)re.test("hoc tu dau"); //true (returns true|false)re.lastIndex;re.source; //"[a-z]"/[0-9]/g.global; //true/[0-9]/m.multiline; //true/[0-9]/i.ignoreCase; //true
HOCTUDAU.COM DANG MINH TUAN
String.prototype
var s = 'Hoc Tu Dau';s.length; //10s.indexOf('u'); //5s.lastIndexOf('u'); //9s.charAt(1); //"o"s.charCodeAt(1); //111s.toLowerCase(); //'hoc tu dau's.toUpperCase(); //HOC TU DAU'
HOCTUDAU.COM DANG MINH TUAN
String.prototype
var s = 'hoc tu dau';s.split(" "); //["hoc", "tu", "dau"] - có thể dùng (/ /)s.replace(/ /g, ""); //"hoctudau"s.concat('.com'); //"hoc tu dau.com"s.search(/tu/); ; //4s.match(/[a-z]/g); ; //["h", "o", "c" ...s.slice(4,6); //"tu"s.substring(0,3); //"hoc"s.substr(0,3); //"hoc"
Number.prototype
new Number(123).toFixed(2); // 123.00(1000000000000).toExponential(); //1e+12(1000000000000).toPrecision(3); //1.00e+12Number.MIN_VALUE; // 5e-324Number.POSITIVE_INFINITY; //InfinityNumber.NaN; //NaN
HOCTUDAU.COM DANG MINH TUAN
Math
Constants● Math.E, Math.PI ... and about 6 moreMethods● Math.min(), Math.max(), ● Math.random(), Math.round(), Math.sin(),● ... and about 14 more ...
HOCTUDAU.COM DANG MINH TUAN
Date
var d = new Date(2012, 12, 21);d.getDate(); //21d.getDay(); //1d.getFullYear(); //2013 !!!d.getMonth(); //0 !!!d.getHours();d.setFullYear(); d.setHours(); ...d.toString(); d.toTimeString(); d.toDateString();...Date.now(); Date.parse(); ...
Q&A & resourceshttp://bit.ly/phpday2012
HOCTUDAU.COM DANG MINH TUAN