javascript 类应该显式返回某些内容吗?
我一直在编写一些 Adobe 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;
}
但是代码在使用 OR 时可以正常工作,而无需最后一个
return rect
所以我的问题是
new rectangle(args);
return if I don't explicitly say so?如果我这样做:
var myRectangle = new rectangle(args);
myRectangle.left = -100;
无论我是否返回矩形,它都可以正常工作。
非常感谢您的帮助。
I've been writing some Adobe Illustrator javascripts to improve my workflow. I've been really getting to grips with OOP recently so I've been writing it using objects and I really think it helps keep my code clean and easily up-datable. However I wanted to check some best practice with you guys.
I have a rectangle object which creates (three guesses)... a rectangle. It looks like this
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;
}
However the code works fine with OR without that last
return rect
So my question is what does
new rectangle(args);
return if I don't explicitly say so?
If I do this:
var myRectangle = new rectangle(args);
myRectangle.left = -100;
It works just fine wether I return rect
or not.
Many thanks for you help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
完全没有必要。当您调用
new
时,将自动创建并分配一个实例。不需要返回this
或类似的东西。在严格的 OOP 语言(如 Java 或 C++)中,构造函数不返回任何内容。
Absolutely unnecessary. An instance will be created and assigned automatically when you call
new
. No need to returnthis
or anything like that.In strictly OOP languages like Java or C++, constructors do not return anything.
你的 javascript 对象应该只有属性和方法。
在方法内使用 return 关键字。
您将如何使用您的对象。
Your javascript object should only have properties and methods.
Use the return keyword inside a method.
How you would use your object.