Bueno por fin he sacado un ratito y he encontrado el caos mental que
tenía con la utilización de this en objetos sin instanciar en jQuery
(minuto 3 de la charla del hyperandroid del otro día).
Aquí el código, simple, sin jQuery y muy chorra.
<html>
<head>
<script type="text/javascript">
var miObj = {
input : null,
button : null,
load : function() {
var that = miObj; // Si funciona
//var that = this; // No funciona :(
that.input = document.getElementById("numero");
that.button = document.getElementById("action");
that.button.addEventListener("click",that.calcula,true);
},
calcula : function() {
var that = miObj; // Si funciona
//var that = this; // No funciona :(
that.button.value = that.input.value * that.input.value;
}
};
window.addEventListener("load",miObj.load,true);
</script>
</head>
<body>
<input type="text" id="numero" /><br />
<input type="button" id="action" value="Al cuadrado" />
</body>
</html>
Creo que la movida es que, al invocar un método encapsulado dentro de
una variable de un módulo (o JSON u objeto simple o {} o como queráis
llamarlo), éste se ejecuta siempre en el contexto de window y no dentro
de su propio contexto...
Bueno sin más, que sabía yo que oía campanas, y ya he visto donde...
cualquier aportación o aclaración molaría ;)
venga nos vemos le miércoles.
--
jabi
|
var miObj = { input : "input", button : "button", load : function() { this.input= 55; }, calcula : function() { var that = this; |
|
that.button.value = that.input.value * that.input.value; } }; |