2. Ako vytvoriť objekt
var o1 = { };
var o2 = new Object();
var o3 = { write: function(a) { console.log(a); } };
o3.write(1);
Rubyslava 21.2.2013 Márius Šajgalík 2
3. Ako vytvoriť objekt
function O4(){
this.write = function(a) { console.log(a); };
}
var O5 = function() {
this.write = function(a) { console.log(a); };
};
var o4 = new O4();
o4.write(1);
Rubyslava 21.2.2013 Márius Šajgalík 3
4. Ako vytvoriť objekt
function Robot(_params) {
var rotor; // private
this.name; // public
function init(params) {
... // compute _rotor from params
rotor = _rotor;
}
init(_params);
}
Rubyslava 21.2.2013 Márius Šajgalík 4
5. Lokálne premenné
function F1() {
var x = 2; // poznáme iba vnútri F1
this.write = function() { console.log(x); };
}
var f1 = new F1();
f1.write();
f1.set = function(x2) { x = x2; }; // nové globálne x
f1.set(3);
f1.write(); // lokálne x nezmenené
console.log(x); // globálne x = 3
Rubyslava 21.2.2013 Márius Šajgalík 5
6. this
function Robot(params){
var name = params.name;
this.getName = function() { return name; };
this.getState = function() {
...
return weather;
};
this.hasUmbrella = function() {
var state = ??? // this.getState is undefined
};
}
Rubyslava 21.2.2013 Márius Šajgalík 6
7. this
function Robot(params){
...
var This = this;
...
this.hasUmbrella = function() {
var state = This.getState();
if (state.rain) return true;
else return false;
};
}
Rubyslava 21.2.2013 Márius Šajgalík 7
8. Ako zmeniť this?
function predstavSa(meno) {
console.log('Ahoj, som ' + this +
' a moje meno je ' + meno);
}
predstavSa.call('robot', 'Wall-E');
predstavSa.apply('robot', ['Wall-E']);
Array.prototype.slice.call('Wall-E', 2, 5)
Rubyslava 21.2.2013 Márius Šajgalík 8
19. Kopírovanie objektov – dedenie
inštancií?
var O = function () {
this.write = function (a) { console.log(a); };
};
var o = new O();
o.write(1);
var p = Object.create(o);
p.write(1);
o.write2 = function (a) { console.log(a + 1); };
o.write2(1);
p.write2 = function (a) { console.log(a - 1); };
o.write2(1);
p.write2(1);
Rubyslava 21.2.2013 Márius Šajgalík 19
20. Ako písať zátvorky?
function areWeFinished()
{
...
}
function areWeFinished() {
...
}
Rubyslava 21.2.2013 Márius Šajgalík 20