views:

53

answers:

2

Hello. 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.

+1  A: 

Absolutely unnecessary. An instance will be created and assigned automatically when you call new. No need to return this or anything like that.

In strictly OOP languages like Java or C++, constructors do not return anything.

Jacob Relkin
Great, thanks! I didn't know that strict OOP constructors didn't return anything.
MrMisterMan
The methods inside the constructor may return 'this' for help in cascading function calls.
Ravindra Sane
@Ravindra good point.
Jacob Relkin
A: 

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();
Q_the_dreadlocked_ninja
I've been developing a pong game in javascript and this method is what I'm using there. I don't know why I'm not doing the same thing in my Illustrator script. One reason I suppose, is it's less verbose without the draw method. Does it matter do you think?
MrMisterMan