84
JavaScript for PHP Stoyan Stefanov March 11, 2011 Confoo.ca, Montreal

Jsphp 110312161301-phpapp02

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Jsphp 110312161301-phpapp02

JavaScript for PHPStoyan StefanovMarch 11, 2011Confoo.ca, Montreal

Page 2: Jsphp 110312161301-phpapp02

Stoyan

 SAP Labs in Montreal

 Yahoo! Music, Web Performance, YSlow, smush.it

 Facebook

Search

Page 3: Jsphp 110312161301-phpapp02

StoyanStefanov -

Page 4: Jsphp 110312161301-phpapp02

JavaScript – first

Page 5: Jsphp 110312161301-phpapp02

DOM/BOM

 These days libraries can take care of most pains

 Let’s focus on the core JavaScript (ECMAScript)

Page 6: Jsphp 110312161301-phpapp02

JavaScript core

 C-like syntax

 Small built-in API  (I’ll show you most of it in 15 minutes)

Page 7: Jsphp 110312161301-phpapp02

Strange

 Functions are objects

 Functions provide scope

 Closures (in PHP since 5.3)

 Prototypes

 No classes

Page 8: Jsphp 110312161301-phpapp02

SyntaMostly the same as PHP

Page 9: Jsphp 110312161301-phpapp02

Variable

var

n = 1;

$n = 1;

Page 10: Jsphp 110312161301-phpapp02

Variable

var

b = true;

$b = true;

Page 11: Jsphp 110312161301-phpapp02

Variable

var

s = "confoo";

$s = "confoo";

Page 12: Jsphp 110312161301-phpapp02

Array

var

a = [1,2,3];

$a = array(1,2,3);

Page 13: Jsphp 110312161301-phpapp02

Assoc

var o =

=

{

"one":

"two":

};

array(

1,

2

$o

"one"

"two"

);

=>

=>

1,

2

Page 14: Jsphp 110312161301-phpapp02

if (1 === 1) {

$universe = "fine";

};

i

if (1 === 1) {

"fine"; universe

};

=

Page 15: Jsphp 110312161301-phpapp02

falsy

0,

"", false, undefined, null

0

0

== "" //

//

true

false === ""

Page 16: Jsphp 110312161301-phpapp02

switc

var

var

a = 1;

result = "";

switch

case

(a)

1:

{

// strict comparison

result

break;

default:

result

= "a is 1";

= "@#$";

}

Page 17: Jsphp 110312161301-phpapp02

try-try {

throw

catch

new

(e)

Error('ouch');

{ }

msg

}

= e.message;

try {

throw

catch

new Exception('ouch');

} (Exception $e) {

$msg = $e->getMessage();

}

Page 18: Jsphp 110312161301-phpapp02

$i = 0; $out = '';

while ($i < 100) {

$out .= ++$i . ",";

}

whil

var i =

(i

0,

<

out = '';

while

out

}

100) {

+= ++i + ",";

Page 19: Jsphp 110312161301-phpapp02

$i = 0; $out = '';

do {

$out .= ++$i . ",";

} while ($i < 100);

do-

var i = 0, out = '';

do {

out += ++i + ",";

} while (i < 100);

Page 20: Jsphp 110312161301-phpapp02

for ($i = 0, $out = ''; $i < 100; $i++) {

$out .= $i . ',';

}

fo

for (var i

i

=

+

0, out = ''; i < 100; i++) {

out += ',';

}

Page 21: Jsphp 110312161301-phpapp02

for-in/

for (var k in stuff) {

keys += k;

values += stuff[k];

}

foreach

$keys

($stuff as $k => $v) {

.= $k;

$values .= $v;

}

Page 22: Jsphp 110312161301-phpapp02

function junction($a, $b) {

return $a * $b;

}

functio

function

return

}

junction(a, b) {

a * b;

Page 23: Jsphp 110312161301-phpapp02

function junction($a, $b = 2) {

return $a * $b;

}

functio

function junction(a, b) {

b = b || 2;

return a * b;

}

Page 24: Jsphp 110312161301-phpapp02

functio

function junction(a, b) {

b = typeof b !== "undefined" ? b : 2;

return a * b;

}

function

return

}

junction($a, $b = 2) {

$a * $b;

Page 25: Jsphp 110312161301-phpapp02

functionsare

var junction = function (a, b) {

return

};

a * b;

junction(3, 4); // 12

junction.length; // 2

Page 26: Jsphp 110312161301-phpapp02

call_user_func('junction', 3, 4);

call_user_func_array('junction', array(3, 4));

functionsare

junction.call(null, 3, 4); // 12

junction.apply(null, [3, 4]); // 12

Page 27: Jsphp 110312161301-phpapp02

$junction = function($a, $b) {

return $a * $b;

};

$junction(3, 4); // 12

closure

var junction = function (a, b) {

return

};

a * b;

junction(3, 4); // 12

Page 28: Jsphp 110312161301-phpapp02

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

Page 29: Jsphp 110312161301-phpapp02

$fido = new Dog();

Constructors/

var

fido = new Dog();

Page 30: Jsphp 110312161301-phpapp02

PHPclass Dog {

var $name;

function construct($name)

{

$this->name = $name;

}

function getName() {

return $this->name;

} $fido = new Dog("Fido");

} $fido->getName(); // Fido

Page 31: Jsphp 110312161301-phpapp02

JS constructorfunction Dog (name) {

this.name = name;

this.getName = function () {

return this.name;

};

}

var fido = new Dog("Fido");

fido.getName();

Page 32: Jsphp 110312161301-phpapp02

JS constructor

 Constructors are just functions

 Functions called with new…

 …return this…

 …implicitly.

Page 33: Jsphp 110312161301-phpapp02

Constructo and prototypfunction Dog (name) {

this.name = name;

}

Dog.prototype.getName = function () {

return this.name;

};

var fido = new Dog("Fido");

fido.getName();

Page 34: Jsphp 110312161301-phpapp02

Prototype

 Every function has a

 It’s useless, unless

prototype property

 … the functions is called with new.

Page 35: Jsphp 110312161301-phpapp02

Constructo and prototypfunction Dog (name) {

this.name = name;

}

Dog.prototype.getName = function () {

return this.name;

};

var fido = new Dog("Fido");

fido.getName(); // Fido

Page 36: Jsphp 110312161301-phpapp02

Object

var fido = {

name: "Fido",

getName:

return

}

};

function()

this.name;

{

fido.getName(); // Fido

Page 37: Jsphp 110312161301-phpapp02

Object

var fido = {};

Page 38: Jsphp 110312161301-phpapp02

Object

var fido = {};

"Fido"; fido.name =

Page 39: Jsphp 110312161301-phpapp02

Object

var fido = {

name:

};

"Fido"

fido.name; // Fido

Page 40: Jsphp 110312161301-phpapp02

Object

var fido = {

name: "Fido",

getName:

return

}

};

function()

this.name;

{

fido.getName(); // Fido

Page 41: Jsphp 110312161301-phpapp02

$fido = (object) array();

$fido->name = "Fido";

$fido = new stdClass();

$fido->name = "Fido";

Literal

var fido = {};

"Fido"; fido.name

=

Page 42: Jsphp 110312161301-phpapp02

Literals in

$fido = (object)array();

$fido->name = 'Fido';

$fido->getName = function() {

return

};

$GLOBALS['fido']->name;

$method = $fido->getName;

echo $method();

Page 43: Jsphp 110312161301-phpapp02

Literals in

$fido = new JSObject();

$fido->name = 'Fido';

$fido->getName = function($self) {

return

};

$self->name;

$fido->getName(); // Fido

Page 44: Jsphp 110312161301-phpapp02

Literals inclass JSObject {

function call($name, $args) {

if (is_callable($this->$name)) {

array_unshift($args, $this);

return call_user_func_array($this->$name, $args);

}

}

}

Page 45: Jsphp 110312161301-phpapp02

Funny

  typeoftypeof 1; // "number"  

  typeof(1);

  instanceof([1,2])

([1,2])

instanceof

instanceof

Array; // true    Object; // true

  deletevar o = {a: 1}; delete o.a; o.a; // undefined  

  voidreturns undefined whatever the operand

Page 46: Jsphp 110312161301-phpapp02

The built-in In 15 minutes or less

Page 47: Jsphp 110312161301-phpapp02

Global object

 something Like $GLOBALS[]

but object

 May or may not be accessible directly

 Accessible as window in browsers

Page 48: Jsphp 110312161301-phpapp02

3 global propertie

 NaN

 Infinity

 undefined

Page 49: Jsphp 110312161301-phpapp02

9 global

 4 number-related  parseInt()

  parseFloat()

  isNaN()

  isFinite()

PHP:intval()

floatval()

is_nan()

is_finite()

 4 to encode/decode URI  encodeURIComponent()

  decodeURIComponent()

  encodeURI()

  decodeURI()

urlencode()

urldecode()

??()

??()

 eval() eval()

Page 50: Jsphp 110312161301-phpapp02

9+

  Object()

  Array()

  RegExp()

  Function()

  String()

  Number()

  Boolean()

  Error(),

  Date()

SyntaxError()…

Page 51: Jsphp 110312161301-phpapp02

We need no constructor

 object literals

// yep

var o = {};

// nope

var o = new Object();

Page 52: Jsphp 110312161301-phpapp02

We need no constructor

 array literals

// yep

var a = [];

// nope

var a = new Array();

Page 53: Jsphp 110312161301-phpapp02

We don’t need no constructor

 regular expression literals // yep

var re = /[a-z]/gmi;

nope // proly

var re = new RegExp("[a-z]", "gmi");

Page 54: Jsphp 110312161301-phpapp02

We don’t need no

 functions

// yep

var f = function(a, b) {return a + b;};

// yep

function f(a, b) {return a + b;}

//

var

nope

f

= new

Function("a, b",

"return a + b;");

Page 55: Jsphp 110312161301-phpapp02

We don’t need no constructor

 strings

// yep

var s = "confoo";

// nope

var

s = new String("confoo");

s.substr(3); // "foo"

"confoo".substr(0, 4); // "conf"

Page 56: Jsphp 110312161301-phpapp02

We don’t need no constructor

 numbers

// yep

var n = 1.2345;

// nope

var

n = new Number(1.2345);

n.toFixed(2); // 1.23

Page 57: Jsphp 110312161301-phpapp02

We need no constructor

 boolean

// yep

var b = true;

// nope, why would you ever

var b = new Boolean(true);

Page 58: Jsphp 110312161301-phpapp02

We don’t need no

 Errors

throw new Error("Ouch");

// but you could also

throw {

name: "MyError",

message:

};

"Ouch"

Page 59: Jsphp 110312161301-phpapp02

ConstructorObject()  

Array()  

RegExp()  

Function()  

String()  

Number()  

Boolean()  

Error(), SyntaxError()…  

 Date()

Page 60: Jsphp 110312161301-phpapp02

The built-in API Properties and methods

Page 61: Jsphp 110312161301-phpapp02

Object.prototype

var o = {};

o.toString(); // "[object Object]"

o.toLocaleString(); // "[object Object]"

o.valueOf() === o; // true

o.hasOwnProperty('toString'); // false

false o.propertyIsEnumerable('toString'); //

o.isPrototypeOf(Array); // false

o.constructor === Object; // true

Page 62: Jsphp 110312161301-phpapp02

Array.prototyp

var a = [1,2,3,4];

a.length; // 4

a.push('dude'); // 5, the length

a.pop(); // "dude"

a.unshift('dude'); // 5, the length

a.shift(); // "dude"

a.concat(5,6,7); // [1,2,3,4,5,6,7]

Page 63: Jsphp 110312161301-phpapp02

Array.prototyp

a.sort(callback);

a.indexOf(3); // 2

a.lastIndexOf(3); // 2

a.slice(1, 3); // [2, 3]

a.splice(...); // remove and add

a.reverse(); // [4, 3, 2, 1]

a.join(' > '); // implode()

Page 64: Jsphp 110312161301-phpapp02

RegExp.prototypvar re = /[a-z]/gmi;

re.exec("somestring");

re.test("somestring");

re.lastIndex;

re.source; // "[a-z]"

//

//

returns

returns

matches

true|false

/[0-9]/g.global;

/[0-9]/m.multiline;

/[0-9]/i.ignoreCase;

//

//

//

true

true

true

Page 65: Jsphp 110312161301-phpapp02

Function.prototyp

 length

 name // not standard

 call()

 apply()

Page 66: Jsphp 110312161301-phpapp02

String.prototyp

var s = "confoo";

s.length; // 6

s.indexOf('o'); // 1

s.lastIndexOf('o'); // 5

s.charAt(1); // "o"

s.charCodeAt(1);

// 111

Page 67: Jsphp 110312161301-phpapp02

String.prototyp

s.toLowerCase();

s.toUppercase();

s.toLocaleLowerCase();

s.toLocaleUpperCase();

s.localeCompare();

Page 68: Jsphp 110312161301-phpapp02

String.prototyp

s.split(/f/); // ["con", "oo"]

s.concat('.ca');

s.search(/foo/);

//

//

"confoo.ca"

3

s.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

Page 69: Jsphp 110312161301-phpapp02

Number.protoypnew Number(123).toFixed(2); // "123.00"

(1000000000000).toExponential();

(1000000000000).toPrecision(3);

//

//

"1e+12"

"1.00e+12"

Number.MAX_VALUE;

Number.MIN_VALUE;

//

//

1.7976931348623157e+308

5e-324

Number.POSITIVE_INFINITY;

Number.NEGATIVE_INFINITY;

//

//

Infinity

-Infinity

Number.NaN; // NaN

Page 70: Jsphp 110312161301-phpapp02

Math

 Not a constructor

 Constants

Math.E,

 Methods

Math.PI... and 6 more

Math.min(), Math.max(),

Math.random(), Math.sin()

... and 14 more

Page 71: Jsphp 110312161301-phpapp02

Error.prototyp

 name

 message

Page 72: Jsphp 110312161301-phpapp02

Date.prototyp

 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.getUTCMonth();d.setFullYear();

d.getUTCMilliseconds(); d.getUTCMinutes();d.getUTCSeconds(); d.getYear(); d.setDate();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();

Page 73: Jsphp 110312161301-phpapp02

Constructor

Object()  

Array()  

RegExp()  

Function()  

String()  

Number() + Math  

Boolean()  

Error(), SyntaxError()…  

Date()  

Page 74: Jsphp 110312161301-phpapp02

QuiWhat have we learned today?

Page 75: Jsphp 110312161301-phpapp02

JavaScript ha classe 

Page 76: Jsphp 110312161301-phpapp02

Arrays object 

Page 77: Jsphp 110312161301-phpapp02

Function are object 

Page 78: Jsphp 110312161301-phpapp02

Classeshave a propertprototype 

Page 79: Jsphp 110312161301-phpapp02

Objects have a propertprototype 

Page 80: Jsphp 110312161301-phpapp02

  Functions property

have a prototype

Page 81: Jsphp 110312161301-phpapp02

Prototype

propertie are use wit 

Page 82: Jsphp 110312161301-phpapp02

phpjs.or

 When you miss a PHP function in JavaScript

Page 83: Jsphp 110312161301-phpapp02

Learnin

 https://developer.mozilla.org/en/JavaScript/Reference

 ECMAScript tweeps: @DmitrySoshnikov,@abozhilov, @kangax,

 http://jsmentors.com

n

http://slidesha r e.ne t /stoya n /

Page 84: Jsphp 110312161301-phpapp02

Thank