代码之家  ›  专栏  ›  技术社区  ›  punkrockbuddyholly

javascript类是否应显式返回某些内容?

  •  1
  • punkrockbuddyholly  · 技术社区  · 14 年前

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

    不管是我,它都很好用 返回记录 或者没有。

    非常感谢你的帮助。

    2 回复  |  直到 14 年前
        1
  •  0
  •   Q_Mlilo    14 年前

    您的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();
    
        2
  •  1
  •   Jacob Relkin    14 年前

    完全没有必要。调用时将自动创建和分配实例 new . 无需返回 this 或者类似的事情。

    严格使用OOP语言,比如 爪哇 C++ 构造函数 不要退回任何东西 .