Pregunta

He escrito algunos archivos JavaScript de Adobe Illustrator para mejorar mi flujo de trabajo. He estado realmente llegar a enfrentarse con programación orientada a objetos recientemente, por lo que he estado escribiendo que el uso de objetos y realmente creo que ayuda a mantener el código limpio y fácilmente-fechable. Sin embargo quería comprobar algunas de las mejores prácticas con ustedes.

Tengo un objeto rectangular que crea (tres oportunidades) ... un rectángulo. Parece que este


function rectangle(parent, coords, name, guide) {

    this.top = coords[0];
    this.left = coords[1];
    this.width = coords[2];
    this.height = coords[3];
    this.parent = (parent) ? parent : doc;  

    var rect = this.parent.pathItems.rectangle(this.top, this.left, this.width, this.height);
    rect.name = (name) ? name : "Path";
    rect.guides = (guide) ? true : false;
    return rect;
}

Sin embargo, el código de bien funciona con o sin esa última

return rect

Así que mi pregunta es lo que hace

retorno
new rectangle(args);
si no lo dice explícitamente?

Si hago esto:


var myRectangle = new rectangle(args);
myRectangle.left = -100;

Funciona muy bien wether I return rect o no.

Muchas gracias por su ayuda.

¿Fue útil?

Solución

Su objeto JavaScript sólo debe tener propiedades y métodos.

Usar la palabra clave return dentro de un método.

function rectangle(parent, coords, name, guide) {

    this.top = coords[0];
    this.left = coords[1];
    this.width = coords[2];
    this.height = coords[3];
    this.parent = (parent) ? parent : doc;  

    this.draw = function () { // add a method to perform an action.
        var rect = this.parent.pathItems.rectangle(this.top, this.left, this.width, this.height);
        rect.name = (name) ? name : "Path";
        rect.guides = (guide) ? true : false;
        return rect;
    };
}

¿Cómo se usaría su objeto.

var myRectangle = new rectangle(args);
    myRectangle.draw();

Otros consejos

absolutamente innecesario. Una instancia se creará y se asigna automáticamente cuando se llama new. No hay necesidad de this retorno o algo por el estilo.

estrictamente programación orientada a objetos lenguajes como Java o C ++ , constructores no devuelve nada .

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top