为什么在JavaScript构造函数中使用副作用是不好的做法? [英] Why is using side effects bad practice in JavaScript constructors?

查看:49
本文介绍了为什么在JavaScript构造函数中使用副作用是不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的设计模式非常相似自定义对象通常在我的代码中.

I use something quite similar to the design pattern custom objects in my code normally.

但是JSLint不赞成这样的构造:

But JSLint frowns upon constructs like this:

function MyClass() { this.init(); }
new MyClass(data);

因为对象在创建后立即被丢弃-它没有用于任何用途.我们可以通过将JSLint分配给变量来愚弄它来忽略它,但这并不会改变JSLint(我猜很多JavaScript爱好者)不鼓励这种模式.

Because the object is being discarded immediately after creation - it isn't being used for anything. We can fool JSLint to ignore this by assigning it to a variable, but it doesn't change that JSLint (and I am guessing many JavaScript enthusiasts) discourages the pattern.

那为什么在JavaScript构造函数中使用副作用被视为不良习惯呢?

So why is using side effects in a JavaScript constructor seen as a bad practice?

对于它的价值,我认为这是一个好的实践,因为:

For what it's worth, I thought this was a good practice because:

  1. 您具有一项设置功能,因此,例如您正在管理MyClass实例列表,以供以后访问.(将对象推到数组上是一种副作用,在构造函数返回良好做法" =难以维护之后,您将不得不这样做.)
  2. 它具有自己的原型,因此是类所有权":Firebug将此报告为MyClass的实例,而不仅仅是Object.(我认为,这使其优于其他设计模式.)

推荐答案

罗伯特·马丁(Robert Martin)在他的书清洁代码中说

In his book Clean Code, Robert Martin says

副作用是谎言.您的函数可以做一件事,但是它确实可以做到其他隐藏的事物也是如此...它们是曲折的且破坏性的误解,常常导致奇怪的时间耦合和顺序依赖性.

Side effects are lies. Your function promises to do one thing, but it also does other hidden things...they are devious and damaging mistruths that often result in strange temporal couplings and order dependencies.

您在评论中描述的关于数组的内容听起来像是奇怪的时间耦合".

What you described in your comment regarding arrays sounds like a "strange temporal coupling".

这篇关于为什么在JavaScript构造函数中使用副作用是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆