Diferència entre revisions de la pàgina «Solucio funcio com a metode»
De wikiserver
| Línia 1: | Línia 1: | ||
| − | < | + | <pre> |
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
function unica(){return this;}; | function unica(){return this;}; | ||
| + | |||
| + | assert(unica() === window, "unica a la finestra"); | ||
var replica = unica; | var replica = unica; | ||
| + | assert(replica() === window, "replicant a la finestra"); | ||
var objecte1 = { | var objecte1 = { | ||
clon : unica | clon : unica | ||
} | } | ||
| + | |||
| + | assert(objecte1.clon() === objecte1, "objecte1 utilitza un clon!"); | ||
var objecte2 = { | var objecte2 = { | ||
| Línia 28: | Línia 18: | ||
} | } | ||
| + | assert(objecte2.clon() === objecte2, "Objecte2 utilitza un clon!"); | ||
| − | + | </pre> | |
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
Revisió del 17:16, 5 nov 2018
function unica(){return this;};
assert(unica() === window, "unica a la finestra");
var replica = unica;
assert(replica() === window, "replicant a la finestra");
var objecte1 = {
clon : unica
}
assert(objecte1.clon() === objecte1, "objecte1 utilitza un clon!");
var objecte2 = {
clon : unica
}
assert(objecte2.clon() === objecte2, "Objecte2 utilitza un clon!");
Exercici
var persona = {
name: 'edu',
twitter: 'eiximenis',
twitterUrl: 'http://twitter.com/' + this.twitter
};
console.log(persona.twitterUrl); //http://twitter.com/undefined
Exercici
// this == window
console.debug(this);
function test(){
// this == window
console.debug(this);
}
test();
Exercici
var obj = {
name: 'obj',
run: function(){
// this == obj
this.value = 1;
console.debug(this.name);
}
};
obj.run();
Exercici
var obj = {
name: 'obj',
run: function(){
this.value = 1;
console.debug(this); // this == obj
(function(){ // se crea un nuevo scope
console.debug(this); // this == window
})();
function test(){ // se crea un nuevo scope
console.debug(this); // this == window
}
test();
}
};
obj.run();
Exercici
var obj = {
name: 'obj',
run: function(){
this.value = 1;
console.debug(this); // this == obj
(function(){
console.debug(this); // this == obj
}).call(this); // se autoejecuta con el método call
this.test = function(){ // se define como método de obj
console.debug(this); // this == obj
}
this.test(); // se ejecuta dentro del contexto de obj
}
};
obj.run();