javascript类应该明确返回一些东西吗?

时间:2010-10-13 08:22:31

标签: javascript oop adobe-illustrator

我一直在编写一些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

,代码可以正常使用OR

所以我的问题是

new rectangle(args);
如果我没有明确说明那么会返回什么?

如果我这样做:


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

它工作得很好return rect我是不是。{/ p>

非常感谢你的帮助。

2 个答案:

答案 0 :(得分:1)

绝对没必要。当您致电new时,将自动创建并分配实例。无需返回this或类似的内容。

在严格的OOP语言中,如 Java C ++ ,构造函数不会返回任何内容

答案 1 :(得分: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();
相关问题