Search code examples
javascriptoopadobe-illustrator

Should a javascript class explicitly return something?


I've been writing some Adobe Illustrator javascripts to improve my workflow. I've been really getting to grips with OOP recently so I've been writing it using objects and I really think it helps keep my code clean and easily up-datable. However I wanted to check some best practice with you guys.

I have a rectangle object which creates (three guesses)... a rectangle. It looks like this


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

However the code works fine with OR without that last

return rect

So my question is what does

new rectangle(args);
return if I don't explicitly say so?

If I do this:


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

It works just fine wether I return rect or not.

Many thanks for you help.


Solution

  • Your javascript object should only have properties and methods.

    Use the return keyword inside a method.

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

    How you would use your object.

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