Upload
elliando-dias
View
1.669
Download
0
Embed Size (px)
DESCRIPTION
Citation preview
JavaScript Everywhere
Thiago Silva<[email protected]>
09/18/07 2
Road map• A linguagem, atualmente ECMA262, 3ed.
– Metaprogramação• A linguagem, amanhã ECMA262, 4ed.• Implementações
– SpiderMonkey (Mozilla C)
– Rhino (Mozilla Java)
– Tamarin (Mozilla C++)
– QSA (Qt C++)
– KJS (KDE C++)
09/18/07 3
Recapitulando...• JavaScript/JScript/ActionScript/ECMAScript• Criada em 1995 para o Netscape 2• Padronizada como ECMA262 (1997)• Última versão: ECMA262, 3ª edição (2000)• ECMA357 (E4X)
"I intended to actually use Scheme..." Brendan Eich
09/18/07 4
Fast Overview• Object oriented (protoype based)• Functional• Javalike syntax• Garbage collected• Dynamically typed
09/18/07 5
O que é, o que é...
09/18/07 6
Built in
09/18/07 7
Orientação à Objeto
09/18/07 8
Natureza dos JS objects
09/18/07 9
Natureza dos JS objects
09/18/07 10
Natureza dos JS objects
09/18/07 11
Natureza dos JS objects
09/18/07 12
Object propertiesvar palestra = new Object;palestra.titulo = "JavaScript Everywhere";palestra.evento = "LinuxChix";
//E, com notação literal:
var palestra = { titulo: "JavaScript Everywhere", evento: "LinuxChix"};
09/18/07 13
Object properties//Duas notações para acessar propriedades
palestra.titulo === palestra["titulo"]
//Exceto quando a chave for um número...
var obj = new Object;obj[0] = "booo";obj[0] === obj.0; //Uops!
09/18/07 14
Object properties
//Eval é caro...
eval("pessoa." + key + " = " + val);
//Que tal...
pessoa[key] = val;
09/18/07 15
Functions//Uma declaração comumfunction soma(x, y) { return x + y;}//Alternativavar soma = new Function("x", "y", "return x + y");
print(soma.length); // 2
var f = function() { arguments.callee(); //recursividade}
09/18/07 16
(Firstclass) Functions//Declaração comumfunction soma(x, y) { return x + y;}
function aplique(func, x, y) { func(x, y);}
aplique(soma, 1, 2);
09/18/07 17
This, that...
print(this); //Global object
09/18/07 18
This, that...function f() {
print(this); //depende!}
f(); //this == Global object
09/18/07 19
This, that...function f() {
print(this); //depende!}
var obj = new Object;
obj.func = f;
obj.func(); //this == obj
palestra.g = f;
palestra.g(); //this == palestra
09/18/07 20
Herança?
• Toda função é uma construtora de objetos• Toda função tem uma propriedade chamada “prototype”• Object, Function, String, Array, etc são funções• Prototype, por default, aponta para Object.prototype (o objeto
primordial)
09/18/07 21
Anatomia
09/18/07 22
Herdando...function Pessoa() {};Function Empregado(){};
Empregado.prototype = new Pessoa();
emp = new Empregado();
09/18/07 23
Extendendo//Extendendo (sem especializar) classes built in
String.prototype.ultimoCaractere = function() {
return this[this.length1];
}
"thiago".ultimoCaractere();
09/18/07 24
ExtendendoArray.prototype.each = function(func) {
for (var i = 0; i < this.length; i++) {
func(this[i])
}
}
[10,7,8].each(function(v) {
print(v); //10, 7, 8});
09/18/07 25
Closuresfunction f() { var local = 99;
return function() { print(local); }}
f()(); //exibe 99
09/18/07 26
Currying Functions• Heim?!?
09/18/07 27
Currying Functionsfunction soma(a,b,c){ if (arguments.length < this.soma.length) { return curry(this.soma,arguments,this); } return a+b+c;} print(add()(1,2,4)); // 7print(add(1)(2)(5)); // 8print(add(1)()(2)()(6)); // 9print(add(1,2,7,8)); // 10
09/18/07 28
Fluent Interfaces//Versão normótica de um código:
function makeOrder(customer) {
var o1 = new Order();
customer.addOrder(o1);
var video = Video.find("The Simpsons");
o1.addItem(video);
video = Video.find("300");
o1.addItem(video);
video = Video.find("Transformers");
video.setSkippable(true);
o1.addItem(video);
o1.setRush(true);
}
09/18/07 29
Fluent Interfaces//Nova versão
function makeFluent(customer) { customer.newOrder(). withVideo("The Simpsons"). withVideo("300"). withVideo("Transformers").skippable(). priorityRush(); }
09/18/07 30
Metaprogramming
• O ato de escrever programas que escrevem programas• O ato de programar as estruturas da linguagem do programa
09/18/07 31
DOM highlevelshow("usstatefield").
when("country").
is("United States");
show("provincefield").
when("country").
is("Canada");
show("brutus").
when("usstate").
is("Ohio, Michigan");
09/18/07 32
REST?var eric = User.find(1)
//GET http://localhost:3000/users/1.xml
var floyd = User.create({
name: "Floyd Wright",
email: "[email protected]"});
//POST http://localhost:3000/users.xml
var chad = User.build({
email: "[email protected]",
name: "Chad Pytel"});
chad.save(); //POST ...
09/18/07 33
ClassesObject.subclass({
nome: "Pessoa",
atributos: ["nome", "email"],
metodos: {
getNome: function() {
return this.nome;
},
setNome: function(nome) {
this.nome = nome;
}
}
});
Pessoa.new().setNome("thiago");
09/18/07 34
JavaScript on Rails?ActiveRecord.subclass({
name: "Pessoa",
has_many: ["livros", "compras"],
validates_presence_of: ["senha"],
class_methods: {
login: function(u,p) {
this.find("all", {
conditions: [["username", u], ["password",p]],
limit: 1,
orderby: "id DESC"
});
}}});
09/18/07 35
Enquanto isso, na sala da justiça...
09/18/07 36
ECMAScript edition 4
• Fases finais• "Compatibilidade" com a ed. 3• Microsoft + Mozilla + Adobe + etc + comunidade• Foco em Programming in the large• Um zilhão de adições
09/18/07 37
Que adições?
09/18/07 38
Classespublic dynamic class Array extends Object
{
public static CASEINSENSITIVE = 1
private static function toString() {
...
}
function join(sep) {
...
}
}
09/18/07 39
Static typing(opcional)
var nome : String = “thiago”;function f(a: int, b: Pessoa) : int { ...}
09/18/07 40
Type parameters(generics)
class List<T> { public add(e: T) { ... } ...}
var pessoas : List<Pessoa>;
09/18/07 41
Block Expressionslet (x=x+10, y=12) { print(x+y);}
print( let (k=k+10, z=12) (k+z, "hello, world!") )
for ( let i=0 ; i < 5 ; i++ ) f(i)
09/18/07 42
Namespacesnamespace debugnamespace releasedebug function trace(s) { print(s) }release function trace(s) { /* do nothing */ } use namespace debugtrace("I will be printed!")
function f() { use namespace release trace("I won't be printed!")}
09/18/07 43
Packagespackage mx.core { class UIObject extends ...}
import acme.core.*var widget : acme.core.Widget
09/18/07 44
Iterators & Generators(+ destr. assignment)
function fib() { let i = 0, j = 1; while (true) { yield i; [i, j] = [j, i + j]; }} var g = fib();for (var i = 0; i < 10; i++) print(g.next());
09/18/07 45
AlternativeClosure Syntax
function(x)xfunction(a,b)[g(),h()]foo(function(x)x,function(y)y,3)
09/18/07 46
Builtin• Classes nativas escritas em JavaScript• Selfhosted
– Compilador
– Typechecker
09/18/07 47
Outras adições...• [[DontEnum]] visível• Proper tail calls• Switch class• Tripple quote strings & String.trim()• Catchalls & getters/setters• Operator overloading
09/18/07 48
E mais outras...• Meta objects• JSON encoding/decoding• Stack inspection• Bug fixes• arguments typeof Array• eval como operador• this bindings
09/18/07 49
E mais outras..
09/18/07 50
Implementações• SpiderMonkey (Mozilla C)• Rhino (Mozilla Java)• Tamarin (Mozilla C++)• QSA (Qt C++)• KJS (KDE C++)
09/18/07 51
Concluíndo• JS é uma linguagem que surpreende muita gente• É pequena, o que a torna sedutora para ser embutida em aplicações• A nova edição, provavelmente, surpreenderá mais ainda.
09/18/07 52
Obrigado• EMail: [email protected]• Jabber: tsilva@jabberbr.org• Blog: http://www.sourcecraft.info/blog