KEMBAR78
Javascript for php developer | PDF
Javascript for
                  PHP Developer
               Đặng Minh Tuấn - hoctudau.com
                      PHP 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ên
 Phá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 JS
               trong 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;               $n = 1;
 $b = true;            $b = true;
 $s = "hoc tu dau";    $s = "hoc tu dau";




HOCTUDAU.COM                                DANG MINH TUAN
Đặt tên biến: Khác
 n=1                  $n = 1;
 $ = 1;
 var n = 1;
 var x = 0, y = '';   $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 = {               $o = array(
             "one":1,              "one"=>1,
             "two":2               "two"=>2
        };                         );
                        PHP 5.4
                        ["one"=>1, "two"=>2]
Bản chất và Nhập dữ liệu
 Javascript: Chạy ở client-side      PHP: chạy ở server và lấy được dữ
 <div id="x">5</div>                 liệu gửi từ client-side lên
 <input id="y">                      <form>
 <script>                                 <input name="y">
 a = document.getElementById("x");        <input type="submit">
 b = a.innerHTML;                    </form>
 c = document.getElementById("y");   <?php
 d = c.value;                             $a = $_GET['y'];




HOCTUDAU.COM                                                    DANG MINH TUAN
Bản chất và Xuất dữ liệu
Javascript: Chạy ở client-side      PHP: chạy ở server và gửi được dữ
<div id="x">5</div>                 liệu xuống client-side
<input id="y">                      <form>
<script>                                 <input name="y">
a = document.getElementById("x");        <input type="submit">
b = a.innerHTML;                    </form>
a.innerHTML = 2 * b;                <?php
c = document.getElementById("y");        $a = $_GET['y'];
d = c.value;                             echo 2 * $a;
c.value = 3 * d;
JS Hello World - Event-Driven Programming
Cú pháp
if (1===1) {...}                      if (1===1) {...}
switch, for, while, do-               switch, for, while, do-
while                                 while
for (var i=0, out=''; i<100; i++) {   for ($i=0, $out=''; $i<100; $i++) {
     out += i + ',';                       $out .= $i . ',';
}                                     }
funtion hoctudau(a,b=2) {             funtion hoctudau($a,$b=2) {
     return a*b;                           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 () {               $a = function () {
     $c =3;                           $c =3;
     $b = function ($a, $b) {         $b = function ($a, $b) {
          return $c * $a * $b;             return $c * $a * $b;
     };                               };
     return $b;                       return $b;
};                               };
$b = $a();                       $b = $a();
alert($b(1, 2)); //6             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ỗi
 try {                           try {
      throw new Error('ouch');        throw new Exception('ouch');
 } catch (e) {                   } catch (Exception $e) {
      msg = e.message;                msg = $e -> getMessage();
 }                               }




HOCTUDAU.COM                                                  DANG MINH TUAN
Toán tử
 nối chuỗi:               nối chuỗi:
 x = 'hoc' + 'tu';        $x = 'hoc' . 'tu';
 x += 'dau'; //hoctudau   $x .= 'dau'; //hoctudau




HOCTUDAU.COM                                DANG MINH TUAN
Constructors/Classes
 var hoctudau = new OnlineCenter();



    $hoctudau = new OnlineCenter();




HOCTUDAU.COM                          DANG MINH TUAN
PHP Class
Class                               class OnlineCenter {
                                        var $name; //PHP 4
                                        public $name; //PHP 5
JS constructor function
                                        function __construct($name) {
function OnlineCenter(name) {
                                             $this->name = $name;
     this.name = name;
                                        }
     this.getName = function () {
                                        function getName() {
          return this.name;
                                             return $this->name;
     }
                                        }
}
                                    }
var hoctudau = new OnlineCenter
                                    $hoctudau = new OnlineCenter
("HocTuDau");
                                    ("HocTuDau");
hoctudau.getName(); //HocTuDau
                                    hoctudau->getName();//HocTuDau
PHP Class
Class                              class OnlineCenter {
                                       var $name; //PHP 4
                                       public $name; //PHP 5
JS Prototype
                                       function __construct($name) {
function OnlineCenter (name) {
                                            $this->name = $name;
     this.name = name;
                                       }
}
                                       function getName() {
OnlineCenter.prototype.getName =
                                            return $this->name;
function() {
                                       }
     return this.name;
                                   }
}
                                   $hoctudau = new OnlineCenter
var hoctudau = new OnlineCenter    ("HocTuDau");
("HocTuDau");
                                   hoctudau->getName();//HocTuDau
hoctudau.getName(); //HocTuDau
Class
 JS Object literal                PHP Literal
 var hoctudau = {                 $hoctudau = (object) array();
      name: "HocTuDau",           $hoctudau->name = 'HocTudau';
                                  $hoctudau->getName = function() {
      getName: function() {
                                       return $GLOBALS['hoctudau']->name;
          return this.name;       };
      }
 };                               $method = $hoctudau->getName;
 hoctudau.getName(); //HocTuDau   echo $method();//HocTuDau




HOCTUDAU.COM                                                        DANG MINH TUAN
Class
JS Object literal                PHP (5.4) Literal
var hoctudau = {                 https://github.com/aviat4ion/JSObject
     name: "HocTuDau",           $hoctudau = new JSObject(
     getName: function() {            'name' => 'HocTuDau';
                                      'getName' => function() {
         return this.name;
                                           return $this->name;
     }                                }
};                               );
hoctudau.getName(); //HocTuDau
                                 $hoctudau->getName();//HocTuDau
Funny JS operators
 typeof
 ● typeof 1; //number
 ● typeof(1);
 instanceof
 ● ([1,2]) instanceof Array; //true
 ● ([1,2]) instanceof Object; //true
 delete
 ● var o = {a:1}; delete o.a; o.a;// undefined


HOCTUDAU.COM                                     DANG MINH TUAN
9 global functions
4 number-related          4 number-related
parseInt()                intval()
parseFloat()              floatval()
isNaN()                   is_nan()
isFinite()                is_finite()
4 to encode/decode URIs   4 to encode/decode URIs
encodeURIComponent()      urlencode()
decodeURIComponent()      urldecode()
encodeURI()               ??
decodeURI()               ??
eval()                    eval()
9+ constructors
Object()
Array()
RegExp()
Function()
String()
Number()
Boolean()
Error(), SyntaxError() ...
Date()
...
Literals
var o = {};                  var o = new Object();
var a = [];                  var a = new Array();
var re = /[a-z]/gmi;         var re = new RegExp("[a-z]", "gmi");
var f = function(..) {...}   var f = new Function("..","...");
function f(..) {...}
var s = 'hoctudau';          var s = new String('hoctudau');
var n = 123;                 var n = new Number(123);
var b = true;                var b = new Boolean(true);
Object.prototype
var o = {};
o.toString(); // "[object Object]"
o.valueOf() === o; //true
o.hasOwnProperty('toString'); //false
o.propertyIsEnumerable('toString'); //false
o.isPrototypeOf(Array); //false
o.constructor === Object; //true
Array.prototype
 var a = [1,2,3,4];
 a.length; // 4
 a.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); //1
 a.lastIndexOf(2); //4
 a.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; //10
 s.indexOf('u'); //5
 s.lastIndexOf('u'); //9
 s.charAt(1); //"o"
 s.charCodeAt(1); //111
 s.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/); ; //4
s.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+12
 Number.MIN_VALUE; // 5e-324
 Number.POSITIVE_INFINITY; //Infinity
 Number.NaN; //NaN




HOCTUDAU.COM                             DANG MINH TUAN
Math
 Constants
 ● Math.E, Math.PI ... and about 6 more
 Methods
 ● 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(); //21
d.getDay(); //1
d.getFullYear(); //2013 !!!
d.getMonth(); //0 !!!
d.getHours();
d.setFullYear(); d.setHours(); ...
d.toString(); d.toTimeString(); d.toDateString();...
Date.now(); Date.parse(); ...
Q&A & resources
                http://bit.ly/phpday2012




HOCTUDAU.COM                               DANG MINH TUAN

Javascript for php developer

  • 1.
    Javascript for PHP Developer Đặng Minh Tuấn - hoctudau.com PHP Day 2012 HOCTUDAU.COM DANG MINH TUAN
  • 2.
    About Me ĐặngMinh 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
  • 3.
    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ên Phát âm: Anh hay Việt? ● PHP ● echo HOCTUDAU.COM DANG MINH TUAN
  • 4.
    Quy ước: mầunền PHP và JS giống nhau: Nền trắng, chữ đen HOCTUDAU.COM DANG MINH TUAN
  • 5.
    Quy ước: mầunền PHP và JS khác nhau: nền đen, chữ trắng HOCTUDAU.COM DANG MINH TUAN
  • 6.
    Phần 1: Vaitrò của JS trong thế giới web hiện đại HOCTUDAU.COM DANG MINH TUAN
  • 7.
    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
  • 8.
    Tại sao lậptrì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
  • 9.
    JS làm đượcgì? 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
  • 10.
    JS làm đượcgì? 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
  • 11.
    Cần học nhữnggì 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
  • 12.
    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
  • 13.
    Tin xấu Vàithứ 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
  • 14.
    Học ở đâuvà 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
  • 15.
    Phần 2: Vàikiế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
  • 16.
    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
  • 17.
    Đặt tên biến:Giống $n = 1; $n = 1; $b = true; $b = true; $s = "hoc tu dau"; $s = "hoc tu dau"; HOCTUDAU.COM DANG MINH TUAN
  • 18.
    Đặt tên biến:Khác n=1 $n = 1; $ = 1; var n = 1; var x = 0, y = ''; $x = 0; $y = ''; HOCTUDAU.COM DANG MINH TUAN
  • 19.
    Khai báo biến:Mảng var a = [1,2,3]; $a = array(1,2,3); HOCTUDAU.COM DANG MINH TUAN
  • 20.
    Khai báo biến:Mảng $a = [1,2,3]; PHP 5.4 $a = [1,2,3]; HOCTUDAU.COM DANG MINH TUAN
  • 21.
    Khai báo biến:Mảng liên kết (assoc) var o = { $o = array( "one":1, "one"=>1, "two":2 "two"=>2 }; ); PHP 5.4 ["one"=>1, "two"=>2]
  • 22.
    Bản chất vàNhập dữ liệu Javascript: Chạy ở client-side PHP: chạy ở server và lấy được dữ <div id="x">5</div> liệu gửi từ client-side lên <input id="y"> <form> <script> <input name="y"> a = document.getElementById("x"); <input type="submit"> b = a.innerHTML; </form> c = document.getElementById("y"); <?php d = c.value; $a = $_GET['y']; HOCTUDAU.COM DANG MINH TUAN
  • 23.
    Bản chất vàXuất dữ liệu Javascript: Chạy ở client-side PHP: chạy ở server và gửi được dữ <div id="x">5</div> liệu xuống client-side <input id="y"> <form> <script> <input name="y"> a = document.getElementById("x"); <input type="submit"> b = a.innerHTML; </form> a.innerHTML = 2 * b; <?php c = document.getElementById("y"); $a = $_GET['y']; d = c.value; echo 2 * $a; c.value = 3 * d;
  • 24.
    JS Hello World- Event-Driven Programming
  • 25.
    Cú pháp if (1===1){...} if (1===1) {...} switch, for, while, do- switch, for, while, do- while while for (var i=0, out=''; i<100; i++) { for ($i=0, $out=''; $i<100; $i++) { out += i + ','; $out .= $i . ','; } } funtion hoctudau(a,b=2) { funtion hoctudau($a,$b=2) { return a*b; return $a*$b; } }
  • 26.
    Closures (Anonymous functions) varhoctudau = 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
  • 27.
    Function Scope: Phạmvi hàm $a = function () { $a = function () { $c =3; $c =3; $b = function ($a, $b) { $b = function ($a, $b) { return $c * $a * $b; return $c * $a * $b; }; }; return $b; return $b; }; }; $b = $a(); $b = $a(); alert($b(1, 2)); //6 echo($b(1, 2)); //Notice: Undefined variable: c //0
  • 28.
    Tạo và gọihà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
  • 29.
    Bắt lỗi try{ try { throw new Error('ouch'); throw new Exception('ouch'); } catch (e) { } catch (Exception $e) { msg = e.message; msg = $e -> getMessage(); } } HOCTUDAU.COM DANG MINH TUAN
  • 30.
    Toán tử nốichuỗi: nối chuỗi: x = 'hoc' + 'tu'; $x = 'hoc' . 'tu'; x += 'dau'; //hoctudau $x .= 'dau'; //hoctudau HOCTUDAU.COM DANG MINH TUAN
  • 31.
    Constructors/Classes var hoctudau= new OnlineCenter(); $hoctudau = new OnlineCenter(); HOCTUDAU.COM DANG MINH TUAN
  • 32.
    PHP Class Class class OnlineCenter { var $name; //PHP 4 public $name; //PHP 5 JS constructor function function __construct($name) { function OnlineCenter(name) { $this->name = $name; this.name = name; } this.getName = function () { function getName() { return this.name; return $this->name; } } } } var hoctudau = new OnlineCenter $hoctudau = new OnlineCenter ("HocTuDau"); ("HocTuDau"); hoctudau.getName(); //HocTuDau hoctudau->getName();//HocTuDau
  • 33.
    PHP Class Class class OnlineCenter { var $name; //PHP 4 public $name; //PHP 5 JS Prototype function __construct($name) { function OnlineCenter (name) { $this->name = $name; this.name = name; } } function getName() { OnlineCenter.prototype.getName = return $this->name; function() { } return this.name; } } $hoctudau = new OnlineCenter var hoctudau = new OnlineCenter ("HocTuDau"); ("HocTuDau"); hoctudau->getName();//HocTuDau hoctudau.getName(); //HocTuDau
  • 34.
    Class JS Objectliteral PHP Literal var hoctudau = { $hoctudau = (object) array(); name: "HocTuDau", $hoctudau->name = 'HocTudau'; $hoctudau->getName = function() { getName: function() { return $GLOBALS['hoctudau']->name; return this.name; }; } }; $method = $hoctudau->getName; hoctudau.getName(); //HocTuDau echo $method();//HocTuDau HOCTUDAU.COM DANG MINH TUAN
  • 35.
    Class JS Object literal PHP (5.4) Literal var hoctudau = { https://github.com/aviat4ion/JSObject name: "HocTuDau", $hoctudau = new JSObject( getName: function() { 'name' => 'HocTuDau'; 'getName' => function() { return this.name; return $this->name; } } }; ); hoctudau.getName(); //HocTuDau $hoctudau->getName();//HocTuDau
  • 36.
    Funny JS operators typeof ● typeof 1; //number ● typeof(1); instanceof ● ([1,2]) instanceof Array; //true ● ([1,2]) instanceof Object; //true delete ● var o = {a:1}; delete o.a; o.a;// undefined HOCTUDAU.COM DANG MINH TUAN
  • 37.
    9 global functions 4number-related 4 number-related parseInt() intval() parseFloat() floatval() isNaN() is_nan() isFinite() is_finite() 4 to encode/decode URIs 4 to encode/decode URIs encodeURIComponent() urlencode() decodeURIComponent() urldecode() encodeURI() ?? decodeURI() ?? eval() eval()
  • 38.
  • 39.
    Literals var o ={}; var o = new Object(); var a = []; var a = new Array(); var re = /[a-z]/gmi; var re = new RegExp("[a-z]", "gmi"); var f = function(..) {...} var f = new Function("..","..."); function f(..) {...} var s = 'hoctudau'; var s = new String('hoctudau'); var n = 123; var n = new Number(123); var b = true; var b = new Boolean(true);
  • 40.
    Object.prototype var o ={}; o.toString(); // "[object Object]" o.valueOf() === o; //true o.hasOwnProperty('toString'); //false o.propertyIsEnumerable('toString'); //false o.isPrototypeOf(Array); //false o.constructor === Object; //true
  • 41.
    Array.prototype var a= [1,2,3,4]; a.length; // 4 a.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
  • 42.
    Array.prototype var a= [3,2,4,1,2]; a.sort; //[1,2,2,3,4] a.indexOf(2); //1 a.lastIndexOf(2); //4 a.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
  • 43.
    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
  • 44.
    String.prototype var s= 'Hoc Tu Dau'; s.length; //10 s.indexOf('u'); //5 s.lastIndexOf('u'); //9 s.charAt(1); //"o" s.charCodeAt(1); //111 s.toLowerCase(); //'hoc tu dau' s.toUpperCase(); //HOC TU DAU' HOCTUDAU.COM DANG MINH TUAN
  • 45.
    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/); ; //4 s.match(/[a-z]/g); ; //["h", "o", "c" ... s.slice(4,6); //"tu" s.substring(0,3); //"hoc" s.substr(0,3); //"hoc"
  • 46.
    Number.prototype new Number(123).toFixed(2);// 123.00 (1000000000000).toExponential(); //1e+12 (1000000000000).toPrecision(3); //1.00e+12 Number.MIN_VALUE; // 5e-324 Number.POSITIVE_INFINITY; //Infinity Number.NaN; //NaN HOCTUDAU.COM DANG MINH TUAN
  • 47.
    Math Constants ●Math.E, Math.PI ... and about 6 more Methods ● Math.min(), Math.max(), ● Math.random(), Math.round(), Math.sin(), ● ... and about 14 more ... HOCTUDAU.COM DANG MINH TUAN
  • 48.
    Date var d =new Date(2012, 12, 21); d.getDate(); //21 d.getDay(); //1 d.getFullYear(); //2013 !!! d.getMonth(); //0 !!! d.getHours(); d.setFullYear(); d.setHours(); ... d.toString(); d.toTimeString(); d.toDateString();... Date.now(); Date.parse(); ...
  • 49.
    Q&A & resources http://bit.ly/phpday2012 HOCTUDAU.COM DANG MINH TUAN