我一直在写一些Adobe Illustrator JavaScripts来改善我的工作流程。我最近一直在与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 或不。

非常感谢您的帮助。

有帮助吗?

解决方案

您的JavaScript对象只能具有属性和方法。

在方法中使用返回关键字。

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();

其他提示

绝对不必要。调用时将自动创建和分配一个实例 new. 。无需返回 this 或类似的东西。

在严格的OOP语言中 爪哇 或者 C ++, ,构造函数 不要退货.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top