0
JavaScript for PHP developersStoyan StefanovMarch 11, 2011Confoo.ca, Montreal
Stoyan Stefanov  SAP Labs in Montreal  Yahoo! Music, Web Performance, Search,  YSlow, smush.it  Facebook
Stoyan Stefanov - Books
JavaScript – first impressions
DOM/BOM  These days libraries can take care of most pains  Let’s focus on the core JavaScript (ECMAScript)  language
JavaScript core  C-like syntax  Small built-in API    (I’ll show you most of it in 15 minutes)
Strange things  Functions are objects  Functions provide scope  Closures (in PHP since 5.3)  Prototypes  No clas...
SyntaxMostly the same as PHP
Variablesvar n = 1;   $n = 1;
Variablesvar b = true;   $b = true;
Variablesvar s = "confoo";   $s = "confoo";
Arraysvar a =      [1,2,3];   $a = array(1,2,3);
Assoc arraysvar o = {             "one": 1,             "two": 2        };   $o = array(             "one" => 1,          ...
ifif (1 === 1) {     universe = "fine";};if (1 === 1) {     $universe = "fine";};
falsy values0, "", false, undefined, null0 == ""   // true0 === "" // false
switchvar a = 1;var result = "";switch (a) {    case 1:    // strict comparison      result = "a is 1";      break;    def...
try-catchtry {    throw new Error(ouch);} catch (e) {    msg = e.message;}try {    throw new Exception(ouch);} catch (Exce...
whilevar i = 0, out = ;while (i < 100) {    out += ++i + ",";}$i = 0; $out = ;while ($i < 100) {    $out .= ++$i . ",";}
do-whilevar i = 0, out = ;do {  out += ++i + ",";} while (i < 100);$i = 0; $out = ;do {  $out .= ++$i . ",";} while ($i < ...
forfor (var i = 0, out = ; i < 100; i++) {    out += i + ,;}for ($i = 0, $out = ; $i < 100; $i++) {    $out .= $i . ,;}
for-in/foreachfor (var k in stuff) {    keys += k;    values += stuff[k];}foreach ($stuff as $k => $v) {    $keys .= $k;  ...
functionfunction junction(a, b) {    return a * b;}function junction($a, $b) {    return $a * $b;}
functionfunction junction(a, b) {    b = b || 2;    return a * b;}function junction($a, $b = 2) {    return $a * $b;}
functionfunction junction(a, b) {    b = typeof b !== "undefined" ? b : 2;    return a * b;}function junction($a, $b = 2) ...
functions are objectsvar junction = function (a, b) {     return a * b;};junction(3, 4); // 12junction.length; // 2
functions are objectsjunction.call(null, 3, 4); // 12junction.apply(null, [3, 4]); // 12call_user_func(junction, 3, 4);cal...
closuresvar junction = function (a, b) {     return a * b;};junction(3, 4); // 12$junction = function($a, $b) {     return...
function scope$a = function() {     $c = 3;     $b = function($a, $b) {          return $c * $a * $b;     };     return $b...
Constructors/Classesvar fido = new Dog();   $fido = new Dog();
PHP Classclass Dog {    var $name;    function     construct($name) {        $this->name = $name;    }    function getName...
JS constructor functionfunction Dog (name) {    this.name = name;    this.getName = function () {         return this.name...
JS constructor function  Constructors are just functions  Functions called with new…  …return this…  …implicitly.
Constructor and prototypefunction Dog (name) {    this.name = name;}Dog.prototype.getName = function () {    return this.n...
Prototypes  Every function has a prototype property  It’s useless, unless …  … the functions is called with new.
Constructor and prototypefunction Dog (name) {    this.name = name;}Dog.prototype.getName = function () {    return this.n...
Object literalsvar fido = {     name: "Fido",     getName: function() {         return this.name;     }};fido.getName(); /...
Object literalsvar fido = {};
Object literalsvar fido = {};fido.name = "Fido";
Object literalsvar fido = {     name: "Fido"};fido.name; // Fido
Object literalsvar fido = {     name: "Fido",     getName: function() {         return this.name;     }};fido.getName(); /...
Literalsvar fido = {};fido.name = "Fido";$fido = (object) array();$fido->name = "Fido";$fido = new stdClass();$fido->name ...
Literals in PHP$fido = (object)array();$fido->name = Fido;$fido->getName = function() {     return $GLOBALS[fido]->name;};...
Literals in PHP$fido = new JSObject();$fido->name = Fido;$fido->getName = function($self) {     return $self->name;};$fido...
Literals in PHPclass JSObject {    function      call($name, $args) {        if (is_callable($this->$name)) {            a...
Funny operators  typeof      typeof 1; // "number"      typeof(1);  instanceof      ([1,2]) instanceof Array; //...
The built-in APIIn 15 minutes or less
Global object  something Like $GLOBALS[]   but object  May or may not be accessible directly  Accessible as window i...
3 global properties  NaN  Infinity  undefined
9 global functions  4 number-related                PHP:    parseInt()                  intval()    parseFloat()    ...
9+ constructors  Object()  Array()  RegExp()  Function()  String()  Number()  Boolean()  Error(),    Synta...
We don’t need no constructors  object literals// yepvar o = {};// nopevar o = new Object();
We don’t need no constructors  array literals// yepvar a = [];// nopevar a = new Array();
We don’t need no constructors  regular expression literals// yepvar re = /[a-z]/gmi;// proly nopevar re = new RegExp("[a...
We don’t need no constructors  functions// yepvar f = function(a, b) {return a + b;};// yepfunction f(a, b) {return a + ...
We don’t need no constructors  strings// yepvar s = "confoo";// nopevar s = new String("confoo");s.substr(3); // "foo""c...
We don’t need no constructors  numbers// yepvar n = 1.2345;// nopevar n = new Number(1.2345);n.toFixed(2); // 1.23
We don’t need no constructors  boolean// yepvar b = true;// nope, why would you evervar b = new Boolean(true);
We don’t need no constructors  Errorsthrow new Error("Ouch");// but you could alsothrow {     name: "MyError",     messa...
Constructors    Object()    Array()    RegExp()    Function()    String()    Number()    Boolean()    Erro...
The built-in API (contd.)Properties and methods
Object.prototypevar o = {};o.toString(); // "[object Object]"o.toLocaleString(); // "[object Object]"o.valueOf() === o; //...
Array.prototypevar a = [1,2,3,4];a.length; // 4a.push(dude); // 5, the lengtha.pop(); // "dude"a.unshift(dude); // 5, the ...
Array.prototypea.sort(callback);a.indexOf(3); // 2a.lastIndexOf(3); // 2a.slice(1, 3);   // [2, 3]a.splice(...); // remove...
RegExp.prototypevar re = /[a-z]/gmi;re.exec("somestring"); // returns matchesre.test("somestring"); // returns true|falser...
Function.prototype  length  name   // not standard  call()  apply()
String.prototypevar s = "confoo";s.length; // 6s.indexOf(o); // 1s.lastIndexOf(o); // 5s.charAt(1); // "o"s.charCodeAt(1);...
String.prototypes.toLowerCase();s.toUppercase();s.toLocaleLowerCase();s.toLocaleUpperCase();s.localeCompare();
String.prototypes.split(/f/); // ["con", "oo"]s.concat(.ca); // "confoo.ca"s.search(/foo/); // 3s.replace(/o/g, "@"); // c...
Number.protoypenew Number(123).toFixed(2); // "123.00"(1000000000000).toExponential(); // "1e+12"(1000000000000).toPrecisi...
Math  Not a constructor  Constants      Math.E, Math.PI... and 6 more  Methods      Math.min(), Math.max(),      Mat...
Error.prototype  name  message
Date.prototype  You’re on your own!var d = new Date(2011, 3, 11);d.getDate(); d.getDay(); d.getFullYear(); d.getHours();...
Constructors  Object()  Array()  RegExp()  Function()  String()  Number() + Math  Boolean()  Error(), Synt...
QuizWhat have we learned today?
  JavaScript has classes      
  Arrays are objects      
  Functions are objects      
  Classes have a prototype property      
  Objects have a prototype property      
  Functions have a prototype property      
  Prototype properties are used with   new      
phpjs.org  When you miss a PHP function in JavaScript
Learning  https://developer.mozilla.org/en/JavaScript/  Reference  ECMAScript tweeps: @DmitrySoshnikov,  @abozhilov, @...
Thank you!
Thank you!
Thank you!
Thank you!
Upcoming SlideShare
Loading in...5
×

Jsphp 110312161301-phpapp02

273

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
273
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
10
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Jsphp 110312161301-phpapp02"

  1. 1. JavaScript for PHP developersStoyan StefanovMarch 11, 2011Confoo.ca, Montreal
  2. 2. Stoyan Stefanov  SAP Labs in Montreal  Yahoo! Music, Web Performance, Search, YSlow, smush.it  Facebook
  3. 3. Stoyan Stefanov - Books
  4. 4. JavaScript – first impressions
  5. 5. DOM/BOM  These days libraries can take care of most pains  Let’s focus on the core JavaScript (ECMAScript) language
  6. 6. JavaScript core  C-like syntax  Small built-in API   (I’ll show you most of it in 15 minutes)
  7. 7. Strange things  Functions are objects  Functions provide scope  Closures (in PHP since 5.3)  Prototypes  No classes
  8. 8. SyntaxMostly the same as PHP
  9. 9. Variablesvar n = 1; $n = 1;
  10. 10. Variablesvar b = true; $b = true;
  11. 11. Variablesvar s = "confoo"; $s = "confoo";
  12. 12. Arraysvar a = [1,2,3]; $a = array(1,2,3);
  13. 13. Assoc arraysvar o = { "one": 1, "two": 2 }; $o = array( "one" => 1, "two" => 2 );
  14. 14. ifif (1 === 1) { universe = "fine";};if (1 === 1) { $universe = "fine";};
  15. 15. falsy values0, "", false, undefined, null0 == "" // true0 === "" // false
  16. 16. switchvar a = 1;var result = "";switch (a) { case 1: // strict comparison result = "a is 1"; break; default: result = "@#$";}
  17. 17. try-catchtry { throw new Error(ouch);} catch (e) { msg = e.message;}try { throw new Exception(ouch);} catch (Exception $e) { $msg = $e->getMessage();}
  18. 18. whilevar i = 0, out = ;while (i < 100) { out += ++i + ",";}$i = 0; $out = ;while ($i < 100) { $out .= ++$i . ",";}
  19. 19. do-whilevar i = 0, out = ;do { out += ++i + ",";} while (i < 100);$i = 0; $out = ;do { $out .= ++$i . ",";} while ($i < 100);
  20. 20. forfor (var i = 0, out = ; i < 100; i++) { out += i + ,;}for ($i = 0, $out = ; $i < 100; $i++) { $out .= $i . ,;}
  21. 21. for-in/foreachfor (var k in stuff) { keys += k; values += stuff[k];}foreach ($stuff as $k => $v) { $keys .= $k; $values .= $v;}
  22. 22. functionfunction junction(a, b) { return a * b;}function junction($a, $b) { return $a * $b;}
  23. 23. functionfunction junction(a, b) { b = b || 2; return a * b;}function junction($a, $b = 2) { return $a * $b;}
  24. 24. functionfunction junction(a, b) { b = typeof b !== "undefined" ? b : 2; return a * b;}function junction($a, $b = 2) { return $a * $b;}
  25. 25. functions are objectsvar junction = function (a, b) { return a * b;};junction(3, 4); // 12junction.length; // 2
  26. 26. functions are objectsjunction.call(null, 3, 4); // 12junction.apply(null, [3, 4]); // 12call_user_func(junction, 3, 4);call_user_func_array(junction, array(3, 4));
  27. 27. closuresvar junction = function (a, b) { return a * b;};junction(3, 4); // 12$junction = function($a, $b) { return $a * $b;};$junction(3, 4); // 12
  28. 28. function scope$a = function() { $c = 3; $b = function($a, $b) { return $c * $a * $b; }; return $b;};$b = $a();$b(1, 2); // 0 in PHP, 6 in JS
  29. 29. Constructors/Classesvar fido = new Dog(); $fido = new Dog();
  30. 30. PHP Classclass Dog { var $name; function construct($name) { $this->name = $name; } function getName() { return $this->name; } $fido = new Dog("Fido");} $fido->getName(); // Fido
  31. 31. JS constructor functionfunction Dog (name) { this.name = name; this.getName = function () { return this.name; };}var fido = new Dog("Fido");fido.getName();
  32. 32. JS constructor function  Constructors are just functions  Functions called with new…  …return this…  …implicitly.
  33. 33. Constructor and prototypefunction Dog (name) { this.name = name;}Dog.prototype.getName = function () { return this.name;};var fido = new Dog("Fido");fido.getName();
  34. 34. Prototypes  Every function has a prototype property  It’s useless, unless …  … the functions is called with new.
  35. 35. Constructor and prototypefunction Dog (name) { this.name = name;}Dog.prototype.getName = function () { return this.name;};var fido = new Dog("Fido");fido.getName(); // Fido
  36. 36. Object literalsvar fido = { name: "Fido", getName: function() { return this.name; }};fido.getName(); // Fido
  37. 37. Object literalsvar fido = {};
  38. 38. Object literalsvar fido = {};fido.name = "Fido";
  39. 39. Object literalsvar fido = { name: "Fido"};fido.name; // Fido
  40. 40. Object literalsvar fido = { name: "Fido", getName: function() { return this.name; }};fido.getName(); // Fido
  41. 41. Literalsvar fido = {};fido.name = "Fido";$fido = (object) array();$fido->name = "Fido";$fido = new stdClass();$fido->name = "Fido";
  42. 42. Literals in PHP$fido = (object)array();$fido->name = Fido;$fido->getName = function() { return $GLOBALS[fido]->name;};$method = $fido->getName;echo $method();
  43. 43. Literals in PHP$fido = new JSObject();$fido->name = Fido;$fido->getName = function($self) { return $self->name;};$fido->getName(); // Fido
  44. 44. Literals in PHPclass JSObject { function call($name, $args) { if (is_callable($this->$name)) { array_unshift($args, $this); return call_user_func_array($this->$name, $args); } }}
  45. 45. Funny 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  void   returns undefined whatever the operand
  46. 46. The built-in APIIn 15 minutes or less
  47. 47. Global object  something Like $GLOBALS[] but object  May or may not be accessible directly  Accessible as window in browsers
  48. 48. 3 global properties  NaN  Infinity  undefined
  49. 49. 9 global functions  4 number-related PHP:   parseInt() intval()   parseFloat() floatval()   isNaN() is_nan()   isFinite() is_finite()  4 to encode/decode URIs   encodeURIComponent() urlencode()   decodeURIComponent() urldecode()   encodeURI() ??()   decodeURI() ??()  eval() eval()
  50. 50. 9+ constructors  Object()  Array()  RegExp()  Function()  String()  Number()  Boolean()  Error(), SyntaxError()…  Date()
  51. 51. We don’t need no constructors  object literals// yepvar o = {};// nopevar o = new Object();
  52. 52. We don’t need no constructors  array literals// yepvar a = [];// nopevar a = new Array();
  53. 53. We don’t need no constructors  regular expression literals// yepvar re = /[a-z]/gmi;// proly nopevar re = new RegExp("[a-z]", "gmi");
  54. 54. We don’t need no constructors  functions// yepvar f = function(a, b) {return a + b;};// yepfunction f(a, b) {return a + b;}// nopevar f = new Function("a, b", "return a + b;");
  55. 55. We don’t need no constructors  strings// yepvar s = "confoo";// nopevar s = new String("confoo");s.substr(3); // "foo""confoo".substr(0, 4); // "conf"
  56. 56. We don’t need no constructors  numbers// yepvar n = 1.2345;// nopevar n = new Number(1.2345);n.toFixed(2); // 1.23
  57. 57. We don’t need no constructors  boolean// yepvar b = true;// nope, why would you evervar b = new Boolean(true);
  58. 58. We don’t need no constructors  Errorsthrow new Error("Ouch");// but you could alsothrow { name: "MyError", message: "Ouch"};
  59. 59. Constructors  Object()  Array()  RegExp()  Function()  String()  Number()  Boolean()  Error(), SyntaxError()…  Date()
  60. 60. The built-in API (contd.)Properties and methods
  61. 61. Object.prototypevar o = {};o.toString(); // "[object Object]"o.toLocaleString(); // "[object Object]"o.valueOf() === o; // trueo.hasOwnProperty(toString); // falseo.propertyIsEnumerable(toString); // falseo.isPrototypeOf(Array); // falseo.constructor === Object; // true
  62. 62. Array.prototypevar a = [1,2,3,4];a.length; // 4a.push(dude); // 5, the lengtha.pop(); // "dude"a.unshift(dude); // 5, the lengtha.shift(); // "dude"a.concat(5,6,7); // [1,2,3,4,5,6,7]
  63. 63. Array.prototypea.sort(callback);a.indexOf(3); // 2a.lastIndexOf(3); // 2a.slice(1, 3); // [2, 3]a.splice(...); // remove and adda.reverse(); // [4, 3, 2, 1]a.join( > ); // implode()
  64. 64. RegExp.prototypevar re = /[a-z]/gmi;re.exec("somestring"); // returns matchesre.test("somestring"); // returns true|falsere.lastIndex;re.source; // "[a-z]"/[0-9]/g.global; // true/[0-9]/m.multiline; // true/[0-9]/i.ignoreCase; // true
  65. 65. Function.prototype  length  name // not standard  call()  apply()
  66. 66. String.prototypevar s = "confoo";s.length; // 6s.indexOf(o); // 1s.lastIndexOf(o); // 5s.charAt(1); // "o"s.charCodeAt(1); // 111
  67. 67. String.prototypes.toLowerCase();s.toUppercase();s.toLocaleLowerCase();s.toLocaleUpperCase();s.localeCompare();
  68. 68. String.prototypes.split(/f/); // ["con", "oo"]s.concat(.ca); // "confoo.ca"s.search(/foo/); // 3s.replace(/o/g, "@"); // c@nf@@s.match(/[a-z]/g); // ["c", "o", "n", ..s.slice(3, 6); // "foo"s.substring(0, 3); // "con", substr() too
  69. 69. Number.protoypenew Number(123).toFixed(2); // "123.00"(1000000000000).toExponential(); // "1e+12"(1000000000000).toPrecision(3); // "1.00e+12"Number.MAX_VALUE; // 1.7976931348623157e+308Number.MIN_VALUE; // 5e-324Number.POSITIVE_INFINITY; // InfinityNumber.NEGATIVE_INFINITY; // -InfinityNumber.NaN; // NaN
  70. 70. Math  Not a constructor  Constants Math.E, Math.PI... and 6 more  Methods Math.min(), Math.max(), Math.random(), Math.sin() ... and 14 more
  71. 71. Error.prototype  name  message
  72. 72. Date.prototype  You’re on your own!var d = new Date(2011, 3, 11);d.getDate(); d.getDay(); d.getFullYear(); d.getHours();d.getMilliseconds(); d.getMinutes(); d.getMonth();d.getSeconds(); d.getTime(); d.getTimezoneOffset();d.getUTCDate(); d.getUTCDay(); d.getUTCFullYear();d.getUTCHours(); d.getUTCMilliseconds(); d.getUTCMinutes();d.getUTCMonth(); d.getUTCSeconds(); d.getYear(); d.setDate();d.setFullYear(); d.setHours(); d.setMilliseconds();d.setMinutes(); d.setMonth(); d.setSeconds(); d.setTime();d.setUTCDate(); d.setUTCFullYear(); d.setUTCHours();d.setUTCMilliseconds(); d.setUTCMinutes(); d.setUTCMonth();d.setUTCSeconds(); d.setYear(); d.toDateString();d.toGMTString(); d.toLocaleDateString(); d.toLocaleFormat();d.toLocaleTimeString(); d.toString(); d.toTimeString();d.toUTCString();Date.now(); Date.parse(); Date.UTC();
  73. 73. Constructors  Object()  Array()  RegExp()  Function()  String()  Number() + Math  Boolean()  Error(), SyntaxError()…  Date()
  74. 74. QuizWhat have we learned today?
  75. 75.   JavaScript has classes 
  76. 76.   Arrays are objects 
  77. 77.   Functions are objects 
  78. 78.   Classes have a prototype property 
  79. 79.   Objects have a prototype property 
  80. 80.   Functions have a prototype property 
  81. 81.   Prototype properties are used with new 
  82. 82. phpjs.org  When you miss a PHP function in JavaScript
  83. 83. Learning  https://developer.mozilla.org/en/JavaScript/ Reference  ECMAScript tweeps: @DmitrySoshnikov, @abozhilov, @kangax, @WebReflection  http://jsmentors.com  Slides: http://slideshare.net/stoyan/
  84. 84. Thank you!
  85. 85. Thank you!
  86. 86. Thank you!
  87. 87. Thank you!
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×