1

我一直在编写一些 Adob​​e Illustrator javascript 来改进我的工作流程。我最近真正掌握了 OOP,所以我一直在使用对象编写它,我真的认为它有助于保持我的代码干净且易于更新。但是我想和你们一起检查一些最佳实践。

我有一个矩形对象,它创建(三个猜测)......一个矩形。看起来像这样


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

然而,代码在没有最后一个的情况下可以正常工作

return rect

所以我的问题是什么

new rectangle(args);
如果我没有明确表示返回?

如果我这样做:


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

不管我return rect与否,它都可以正常工作。

非常感谢您的帮助。

4

2 回答 2

1

完全没有必要。调用时会自动创建并分配一个实例new。无需返回this或类似的东西。

在JavaC++等严格的 OOP 语言中,构造函数不返回任何内容

于 2010-10-13T08:27:37.803 回答
0

你的 javascript 对象应该只有属性和方法。

在方法中使用 return 关键字。

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

你将如何使用你的对象。

var myRectangle = new rectangle(args);
    myRectangle.draw();
于 2010-10-13T08:49:05.890 回答