void方法和return this有什么区别 [英] What is the difference between void method and return this

查看:55
本文介绍了void方法和return this有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Class Player {
Player setName(String name){
this.name = name;
return this;

// or

void setName(String name){
this.name = name;
}}

嗨.如果我使用带有void"或return this"语句的方法有什么区别?为什么存在return this"语句,如果它的作用相同?

Hi. What is the difference if I use the method with "void" or "return this" statement? Why the "return this" statement exists, if it does the same?

推荐答案

为什么存在return this"语句,如果它的作用相同?

Why the "return this" statement exists, if it does the same?

他们不会远程做同样的事情.

They don't remotely do the same thing.

void 方法没有返回值.这意味着您不能使用返回值(例如,您不能将其分配给变量).

A void method has no return value. That means you can't use the return value (for instance, you can't assign it to a variable).

有返回值的方法有返回值.在您提到的特定情况下,return this,它返回对调用该方法的对象的引用,因此您可以(可能)使用该引用 —通过将它分配给一个变量,通过调用另一个方法等等.这对于 流畅的接口很有用(允许您进行大量链接的那些):

A method with a return value has a return value. In the particular case you've mentioned, return this, it's returning a reference to the object that the method was called on, so you can (potentially) use that reference — by assigning it to a variable, by calling another method on it, etc. This is useful for fluent interfaces (ones that allow you to do a lot of chaining):

theObject.doThis().thenDoThat().thenDoSomethingElse();

如果它是 void,你必须这样写:

If it were void instead, you'd have to write that like this:

theObject.doThis();
theObject.thenDoThat();
theObject.thenDoSomethingElse();

可能最著名的例子1构建器模式对象构造,因为这意味着您不需要变量:

Probably the most famous example of this1 is Builder pattern of object construction, because it means you don't need a variable:

Thingy t = new ThingyBuilder()
    .withFoo("foo")
    .withBar("bar")
    .withBaz("baz")
    .build();

<小时>

1 Web 开发圈外最著名的,就是; Web 开发圈中,最著名的例子是 jQuery 的 API:$("div").css("color", "green").text("Good");


1 Most famous outside web development circles, that is; inside web development circles, the most famous example would be jQuery's API: $("div").css("color", "green").text("Good");

这篇关于void方法和return this有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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