简单的检索和赋值获取器和设置器在JavaScript中有用吗? [英] Are simple retrieval and assignment getters and setters useful in JavaScript?

查看:70
本文介绍了简单的检索和赋值获取器和设置器在JavaScript中有用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对JavaScript中的每个属性重复此模式是否有意义?

Is there any point in repeating this pattern for every property in JavaScript?

class Thing {
  get myProp() {
    return this._myProp;
  }
  set myProp(value) {
    this._myProp = value;
  }
}

我知道,如果您要在方法中进行其他工作,则getter/setter方法会很有用,但是在此处重新创建基本功能似乎是不必要的重复.如果我实例化了,我仍然可以直接操作backing属性(._myProp),因此我觉得可以轻松地省去这些,并以更典型的即席方式进行分配和访问.

I understand that getters/setters can be useful if you're doing additional work in the methods, but recreating the basic functionality here seems like needless repetition. If I instantiate, I can still manipulate the backing property (._myProp) directly, so I feel like I could just as easily leave these out and perform my assignment and access in the more typical, ad-hoc fashion.

我想您可能会争辩说,以这种方式定义接口(带有下划线前缀的属性名称)会向用户发出信号,它并不意味着要操纵该属性,但这似乎是脆弱的原因,可能导致数十种此类行为.

I suppose you could argue that defining the interface this way (with the underscore-prefixed property name) signals to users that it's not meant to manipulate the property, but that seems like a flimsy reason for potentially dozens of these.

推荐答案

在编译语言中,人们通常这样做.这是因为在这些语言中,分配给字段和调用设置器可能与程序员相同,但是它们会编译为两个完全不同的操作.

In compiled languages, it's common for people to do this. This is because in those languages, assigning to a field and invoking a setter may be identical to the programmer, but they compile to two completely different operations.

例如,如果我想添加一个副作用来设置C#类中的字段,而该字段是直接设置的,而不是通过setter设置的?将其更改为设置器将导致一些问题.我不必重写任何消耗代码,但是我将必须重新编译所有这些代码.如果编译您的公开发布,这当然是一个巨大的问题.

If I wanted to add a side effect for setting a field in a C# class, for example, and that field was being set directly instead of through a setter? Changing it to a setter would cause some issues. I wouldn't have to rewrite any of the consuming code, but I would have to recompile all of it. This is, of course, a huge problem if your public releases are compiled.

但是,JavaScript不受此类考虑,因此过早地将所有内容放入吸气剂/装填器中是一种愚蠢的做法.如果您看到有人这样做,则很可能是在与从另一种语言学习了约定并将其带入JavaScript的人打交道,而没有想太多为什么.

JavaScript is subject to no such considerations, though, so making everything into a getter/setter prematurely is kind of silly. If you see someone doing this, more than likely you're dealing with someone who learned the convention from another language and carried it into JavaScript, without thinking a whole lot about why.

这篇关于简单的检索和赋值获取器和设置器在JavaScript中有用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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