Question

J'ai écrit quelques javascripts Adobe Illustrator pour améliorer mon flux de travail. J'ai vraiment prise en main avec POO récemment donc j'ai écrit à l'aide d'objets et je pense vraiment aide à garder mon code propre et facilement-datable. Cependant, je voulais vérifier certaines bonnes pratiques avec vous les gars.

J'ai un objet rectangle qui crée (trois suppositions) ... un rectangle. Il ressemble à ceci


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;
}

Cependant, le code fonctionne bien avec ou sans cette dernière

return rect

Alors, ma question est qu'est-ce que

retour
new rectangle(args);
si je ne dis pas explicitement?

Si je fais ceci:


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

Il fonctionne très bien wether je return rect ou non.

Merci pour votre aide.

Était-ce utile?

La solution

Votre objet javascript ne doit avoir des propriétés et méthodes.

Utilisez le mot-clé de retour dans une méthode.

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;
    };
}

Comment vous utilisez votre objet.

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

Autres conseils

Tout à fait inutile. Une instance sera créé et attribué automatiquement lorsque vous appelez new. Pas besoin de this de retour ou quelque chose comme ça.

Dans strictement POO langues comme Java ou C ++ , les constructeurs ne rien retourner .

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top