domingo, 26 de julio de 2015

Clase Punto en Javascript usando Joose

Javascript


En Javascript vamos a implementar una clase Punto con los atributos x e y usando el namespace Test.
if(Test == null) {
    Test = {};
}
Test.StandardPoint = function (x, y) {
    this.x = x || 0
    this.y = y || 0
}
Test.StandardPoint.prototype = {
    getX: function () {
        return this.x
    },
    setX: function (x) {
        this.x = x
    },
    getY: function () {
        return this.y
    },
    setY: function (y) {
        this.y = y;
    },
    clear: function () {
        this.setX(0)
        this.setY(0)
    }
}

Joose


Ahora reimplementamos la clase Punto usando la librería Joose y vemos que el nuevo código es más corto y fácil de leer.
Module("Test", function (m) {
    Class("Point", {
        has: {
            x: {
                is:   "rw",
                init: 0
            },
            y: {
                is:   "rw",
                init: 0
            }
        },
        methods: {
            clear: function () {
                this.setX(0);
                this.setY(0);
            }
        }
    })
})

No hay comentarios:

Publicar un comentario