Poniższe konstrukcje są równoważne: obiekt.pole1 = wartość; obiekt.pole2 = wartość; i with (obiekt) { pole1 = wartość; pole2 = wartość; }
Definiowanie klas dla obiektów Aby zdefiniować własny obiekt, wystarczy utworzyć funkcję konstruktora:
// funkcja konstruktora function MójObiekt(poleA, poleB) { this.poleA = poleA; this.poleB = poleB;
this.metoda1 = function() { alert("mójObiekt::metoda1()");
this.metoda2 = function() { alert("mójObiekt::metoda2()");
}Podobnie, choć lżejszy obiekt można uzyskać następująco:// funkcja konstruktora function MójObiekt(poleA, poleB) { this.poleA = poleA; this.poleB = poleB; } // metody MójObiekt.prototype.metoda1 = function() { alert("mójObiekt::metoda1()"); }; MójObiekt.prototype.metoda2 = function() { alert("mójObiekt::metoda2()"); };Od ES2015 wprowadzono lukier składniowy do definiowania klas (pod spodem nadal używany jest prototyp):class MójObiekt { constructor(poleA, poleB) { this.poleA = poleA; this.poleB = poleB;
metoda1() { alert("mójObiekt::metoda1()");
metoda2() { alert("mójObiekt::metoda2()");
Aby utworzyć instancję klasy , należy skorzystać z operatora :
let m = new MójObiekt(2, 3);