Diferència entre revisions de la pàgina «JavaScript: Objectes»
De Wikimir
(→Definició d'un prototip. Mètodes) |
(→Definició d'un prototip. Mètodes) |
||
| Línia 35: | Línia 35: | ||
document.write ("L'alumne " + this.nom + " ha estudiat avui " + hores + " hores.<br>"); | document.write ("L'alumne " + this.nom + " ha estudiat avui " + hores + " hores.<br>"); | ||
} | } | ||
| − | + | ||
// El mètode el definim fora, però el declarem dins | // El mètode el definim fora, però el declarem dins | ||
this.dormir=dorm; | this.dormir=dorm; | ||
} | } | ||
| − | + | ||
function dorm () { | function dorm () { | ||
document.write("Els estudiants també necessitem dormir!<br>"); | document.write("Els estudiants també necessitem dormir!<br>"); | ||
} | } | ||
| − | + | ||
// Tot ho fem fora. | // Tot ho fem fora. | ||
alumne.prototype.examinarse = function (nota) { | alumne.prototype.examinarse = function (nota) { | ||
Revisió del 20:13, 25 oct 2016
En aquest article de JavaScript s'aborden les funcions.
La POO a Javascript
JavaScript és també un llenguatge orientat a objectes, però la manera en què implementa els objectes és diferent a altres llenguatges OO, com C++ o Java.
A JavaScript TOT són objectes: els tipus de dades, les variables, les funcions.
Definició d'un prototip. Propietats
// funció constructora del prototip alumne
var alumne = function (n, cog1, ed) {
this.nom = n;
this.cognom1 = cog1;
this.edat = ed;
}
// Creem un objecte alumne, seguint la definició de la funció constructora
alume1 = new alumne(“Joan”, “Garcia”, 32);
document.write (“L'alumne es diu ” + alumne1.nom + “ ” + alumne1.cognom1 + “
i té ” + alumne1.edat + “ anys.”);
Definició d'un prototip. Mètodes
var alumne = function (n, cog1, ed) {
this.nom = n;
this.cognom1 = cog1;
this.edat = ed;
// Declarem i definim el mètode a dintre de la definició de l'objecte
this.estudiar=function(hores){
document.write ("L'alumne " + this.nom + " ha estudiat avui " + hores + " hores.<br>");
}
// El mètode el definim fora, però el declarem dins
this.dormir=dorm;
}
function dorm () {
document.write("Els estudiants també necessitem dormir!<br>");
}
// Tot ho fem fora.
alumne.prototype.examinarse = function (nota) {
document.write("L'alumne " + this.nom + " ha tret un " + nota + " a l'examen.<br>");
}
alumne1 = new alumne ('Joan', 'Garcia', 32);
alumne1.estudiar (5);
alumne1.examinarse (7);
alumne1.dormir();