Jsphp 110312161301-phpapp02

Post on 15-Jan-2015

247 views 0 download

Tags:

description

 

Transcript of Jsphp 110312161301-phpapp02

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

Stoyan

 SAP Labs in Montreal

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

 Facebook

Search

StoyanStefanov -

JavaScript – first

DOM/BOM

 These days libraries can take care of most pains

 Let’s focus on the core JavaScript (ECMAScript)

JavaScript core

 C-like syntax

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

Strange

 Functions are objects

 Functions provide scope

 Closures (in PHP since 5.3)

 Prototypes

 No classes

SyntaMostly the same as PHP

Variable

var

n = 1;

$n = 1;

Variable

var

b = true;

$b = true;

Variable

var

s = "confoo";

$s = "confoo";

Array

var

a = [1,2,3];

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

Assoc

var o =

=

{

"one":

"two":

};

array(

1,

2

$o

"one"

"two"

);

=>

=>

1,

2

if (1 === 1) {

$universe = "fine";

};

i

if (1 === 1) {

"fine"; universe

};

=

falsy

0,

"", false, undefined, null

0

0

== "" //

//

true

false === ""

switc

var

var

a = 1;

result = "";

switch

case

(a)

1:

{

// strict comparison

result

break;

default:

result

= "a is 1";

= "@#$";

}

try-try {

throw

catch

new

(e)

Error('ouch');

{ }

msg

}

= e.message;

try {

throw

catch

new Exception('ouch');

} (Exception $e) {

$msg = $e->getMessage();

}

$i = 0; $out = '';

while ($i < 100) {

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

}

whil

var i =

(i

0,

<

out = '';

while

out

}

100) {

+= ++i + ",";

$i = 0; $out = '';

do {

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

} while ($i < 100);

do-

var i = 0, out = '';

do {

out += ++i + ",";

} while (i < 100);

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

$out .= $i . ',';

}

fo

for (var i

i

=

+

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

out += ',';

}

for-in/

for (var k in stuff) {

keys += k;

values += stuff[k];

}

foreach

$keys

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

.= $k;

$values .= $v;

}

function junction($a, $b) {

return $a * $b;

}

functio

function

return

}

junction(a, b) {

a * b;

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

return $a * $b;

}

functio

function junction(a, b) {

b = b || 2;

return a * b;

}

functio

function junction(a, b) {

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

return a * b;

}

function

return

}

junction($a, $b = 2) {

$a * $b;

functionsare

var junction = function (a, b) {

return

};

a * b;

junction(3, 4); // 12

junction.length; // 2

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

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

return $a * $b;

};

$junction(3, 4); // 12

closure

var junction = function (a, b) {

return

};

a * b;

junction(3, 4); // 12

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

$fido = new Dog();

Constructors/

var

fido = new Dog();

PHPclass Dog {

var $name;

function construct($name)

{

$this->name = $name;

}

function getName() {

return $this->name;

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

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

JS constructorfunction Dog (name) {

this.name = name;

this.getName = function () {

return this.name;

};

}

var fido = new Dog("Fido");

fido.getName();

JS constructor

 Constructors are just functions

 Functions called with new…

 …return this…

 …implicitly.

Constructo and prototypfunction Dog (name) {

this.name = name;

}

Dog.prototype.getName = function () {

return this.name;

};

var fido = new Dog("Fido");

fido.getName();

Prototype

 Every function has a

 It’s useless, unless

prototype property

 … the functions is called with new.

Constructo and prototypfunction Dog (name) {

this.name = name;

}

Dog.prototype.getName = function () {

return this.name;

};

var fido = new Dog("Fido");

fido.getName(); // Fido

Object

var fido = {

name: "Fido",

getName:

return

}

};

function()

this.name;

{

fido.getName(); // Fido

Object

var fido = {};

Object

var fido = {};

"Fido"; fido.name =

Object

var fido = {

name:

};

"Fido"

fido.name; // Fido

Object

var fido = {

name: "Fido",

getName:

return

}

};

function()

this.name;

{

fido.getName(); // Fido

$fido = (object) array();

$fido->name = "Fido";

$fido = new stdClass();

$fido->name = "Fido";

Literal

var fido = {};

"Fido"; fido.name

=

Literals in

$fido = (object)array();

$fido->name = 'Fido';

$fido->getName = function() {

return

};

$GLOBALS['fido']->name;

$method = $fido->getName;

echo $method();

Literals in

$fido = new JSObject();

$fido->name = 'Fido';

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

return

};

$self->name;

$fido->getName(); // Fido

Literals inclass JSObject {

function call($name, $args) {

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

array_unshift($args, $this);

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

}

}

}

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

The built-in In 15 minutes or less

Global object

 something Like $GLOBALS[]

but object

 May or may not be accessible directly

 Accessible as window in browsers

3 global propertie

 NaN

 Infinity

 undefined

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()

9+

  Object()

  Array()

  RegExp()

  Function()

  String()

  Number()

  Boolean()

  Error(),

  Date()

SyntaxError()…

We need no constructor

 object literals

// yep

var o = {};

// nope

var o = new Object();

We need no constructor

 array literals

// yep

var a = [];

// nope

var a = new Array();

We don’t need no constructor

 regular expression literals // yep

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

nope // proly

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

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;");

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"

We don’t need no constructor

 numbers

// yep

var n = 1.2345;

// nope

var

n = new Number(1.2345);

n.toFixed(2); // 1.23

We need no constructor

 boolean

// yep

var b = true;

// nope, why would you ever

var b = new Boolean(true);

We don’t need no

 Errors

throw new Error("Ouch");

// but you could also

throw {

name: "MyError",

message:

};

"Ouch"

ConstructorObject()  

Array()  

RegExp()  

Function()  

String()  

Number()  

Boolean()  

Error(), SyntaxError()…  

 Date()

The built-in API Properties and methods

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

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]

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()

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

Function.prototyp

 length

 name // not standard

 call()

 apply()

String.prototyp

var s = "confoo";

s.length; // 6

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

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

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

s.charCodeAt(1);

// 111

String.prototyp

s.toLowerCase();

s.toUppercase();

s.toLocaleLowerCase();

s.toLocaleUpperCase();

s.localeCompare();

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

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

Math

 Not a constructor

 Constants

Math.E,

 Methods

Math.PI... and 6 more

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

Math.random(), Math.sin()

... and 14 more

Error.prototyp

 name

 message

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();

Constructor

Object()  

Array()  

RegExp()  

Function()  

String()  

Number() + Math  

Boolean()  

Error(), SyntaxError()…  

Date()  

QuiWhat have we learned today?

JavaScript ha classe 

Arrays object 

Function are object 

Classeshave a propertprototype 

Objects have a propertprototype 

  Functions property

have a prototype

Prototype

propertie are use wit 

phpjs.or

 When you miss a PHP function in JavaScript

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 /

Thank