强制显式使用 this/self 指针有什么好处?
拥有 this
/self
/me
指针强制明确吗?
根据 OOP 理论,方法应该主要(仅?)对成员变量进行操作,并且方法的参数。 在此之后,引用成员变量应该比引用外部(从对象的角度来看)变量更容易......显式this
使其更加冗长,因此引用成员变量比引用外部变量更难。 这对我来说似乎违反直觉。
What is the advantage of having this
/self
/me
pointer mandatory explicit?
According to OOP theory a method is supposed to operate mainly (only?) on member variables and method's arguments. Following this, it should be easier to refer to member variables than to external (from the object's side of view) variables... Explicit this
makes it more verbose thus harder to refer to member variables than to external ones. This seems counter intuitive to me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要它来将指针/引用传递到其他地方的当前对象,或者防止赋值运算符中的自赋值。
You need it to pass the pointer/reference to the current object elsewhere or to protect against self-assignment in an assignment operator.
如果方法的参数与成员变量同名怎么办? 然后您可以使用
this.x = x
例如。 其中this.x
是成员变量,x
是方法参数。这只是一个(微不足道的)例子。
What if the arguments to a method have the same name as the member variables? Then you can use
this.x = x
for example. Wherethis.x
is the member variable andx
is the method argument.That's just one (trivial) example.
我通常仅在编写赋值运算符或复制构造函数时使用它(在C++中),因为它有助于清楚地识别变量。 我可以考虑使用它的其他地方是,如果您的函数参数变量名称与成员变量名称相同,或者我想使用删除此来杀死我的对象。
I generally use this (in C++) only when I am writing the assignment operator or the copy constructor as it helps in clearly identifying the variables. Other place where I can think of using it is if your function parameter variable names are same as your member variable names or I want to kill my object using delete this.
例如,成员名称与传递给方法的成员名称相同
Eg would be where member names are same as those passed to method
除了成员变量和方法参数之外,您还有局部变量。 关于对象最重要的事情之一是它的内部状态。 显式成员变量取消引用可以非常清楚地表明您在何处引用该状态以及在何处修改该状态。
例如,如果您有这样的代码:
当快速浏览它时,您必须对前一段中定义的变量有一个心理模型,以了解它是否只是一个临时变量或者是否会改变对象状态。 而 this.foo = 42 很明显对象状态发生了变化。 如果专门使用显式解引用,则可以确保该变量在相反情况下是临时的。
较短、分解良好的方法使其不再那么重要,但长期的可理解性仍然胜过编写代码时的便利性。
In addition to member variables and method parameters you also have local variables. One of the most important things about the object is its internal state. Explicit member variable dereferencing makes it very clear where you are referencing that state and where you are modifying that state.
For instance, if you have code like:
when quickly browsing through it, you have to have a mental model of the variables defined in the preceding segment to know if it's just a temporary variable or does it mutate the objects state. Whereas this.foo = 42 makes it obvious that the objects state is mutated. And if explicit dereferencing is exclusively used, you can be sure that the variable is temporary in the opposite case.
Shorter, well factored methods make it a bit less important, but still, long term understandability trumps a little convenience while writing the code.