【问题标题】:Should a javascript class explicitly return something?javascript 类应该显式返回一些东西吗?
【发布时间】:2010-10-13 16:49:05
【问题描述】:

我一直在编写一些 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,它都可以正常工作。

非常感谢您的帮助。

【问题讨论】:

  • 您可以通过单击向上箭头来支持我的回答。您应该通过单击我的答案旁边的空心复选标记来接受您的问题的答案。
  • 我尝试过投票,但恐怕我没有足够的声誉。你能接受多个答案吗?我的理解是你等待一段时间并接受最好的?你的答案很好,但我还不知道其他人会说什么。还是我没听懂?

标签: javascript oop adobe-illustrator


【解决方案1】:

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

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

【讨论】:

  • 太好了,谢谢!我不知道严格的 OOP 构造函数没有返回任何东西。
  • 构造函数内部的方法可能会返回'this'以帮助级联函数调用。
【解决方案2】:

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

【讨论】:

  • 我一直在用javascript开发一个乒乓球游戏,这个方法就是我在那里使用的。我不知道为什么我不在 Illustrator 脚本中做同样的事情。我想的一个原因是,如果没有 draw 方法,它就不那么冗长了。你觉得重要吗?
猜你喜欢
  • 1970-01-01
  • 2010-10-22
  • 1970-01-01
  • 2011-09-07
  • 2013-12-31
  • 1970-01-01
  • 2017-07-29
  • 2017-03-02
  • 2020-10-14
相关资源
最近更新 更多