28.05.2013 Views

javascript by example

javascript by example

javascript by example

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Capitolo 1<br />

var obj = {};<br />

Linguaggio<br />

All'oggetto creato, come vedremo, è possibile associare proprietà<br />

e metodi a piacere, tuttavia è anche possibile definire<br />

una funzione “costruttore” per stabilire in anticipo quali saranno<br />

i membri dell'oggetto o magari per consentire di passare<br />

degli argomenti in fase di costruzione con l'operatore new.<br />

//costruttore con argomenti<br />

function Auto (posti, marca, targa){<br />

// this rappresenta l'oggetto che verrà creato<br />

}<br />

this.posti = posti;<br />

this.marca = marca;<br />

this.targa = targa;<br />

//dichiaro l'oggetto utilizzando il modello Auto<br />

var auto1 = new Auto (4,'Fiat 500','TO23443');<br />

var auto2 = new Auto (4,'Citroen 2 cv','DX234ED');<br />

//utilizzo una proprietà<br />

document.write(auto1.marca);<br />

Da notare che, a differenza di quanto si potrebbe credere, Auto non<br />

è un Tipo a se stante, ma semplicemente un modello per creare un<br />

oggetto con determinate caratteristiche, scrivere infatti :<br />

var auto1 = new Auto (4,'Fiat 500','TO23443');<br />

o scrivere<br />

var auto1 = new Object;<br />

auto1.posti = 4;<br />

auto1.marca = 'Fiat 500';<br />

auto1.targa ='TO23443';<br />

I libri di ioPROGRAMMO/Javascript <strong>by</strong> Example 29<br />

JAVASCRIPT<br />

BY EXAMPLE

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!