2010-10-13 55 views
1

我一直在写一些Adobe Illustrator JavaScripts来改善我的工作流程。最近我一直非常关注OOP,所以我一直在使用对象编写它,并且我认为它有助于保持我的代码清洁且易于修改。不过,我想和你们一起检查一些最佳做法。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; 

    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与否。

非常感谢您的帮助。

+1

您可以通过点击向上箭头来调高我的答案。您应该通过点击我答案旁边的空白复选标记来接受您的问题的答案。 – 2010-10-13 08:46:21

+0

我尝试了upvoting它,但我没有足够的声誉,我害怕。你能接受多个答案吗?我的理解是你等待一段时间,接受最好的一个?你的回答非常好,但我还不知道别人会说些什么。或者我没有得到它? – MrMisterMan 2010-10-13 09:10:27

回答

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

我一直在JavaScript中开发pong游戏,这种方法就是我在那里使用的。我不知道为什么我在Illustrator脚本中没有做同样的事情。我猜想的一个原因是,如果没有绘制方法,它就不那么冗长了。你觉得这有什么关系吗? – MrMisterMan 2010-10-13 09:04:45

1

绝对没有必要。当您拨打new时,将自动创建并分配一个实例。无需返回this或类似的东西。

在严格的OOP语言如Java的C++,构造不返回任何

+1

太好了,谢谢!我不知道严格的OOP构造函数没有返回任何东西。 – MrMisterMan 2010-10-13 08:45:14

+1

构造函数中的方法可能会返回'this'以获得级联函数调用的帮助。 – 2010-10-13 09:50:36

+0

@Ravindra好点。 – 2010-10-13 09:57:00

相关问题