且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

this 指的是当前对象.但无法理解以下行为

更新时间:2023-11-05 13:31:10

当前对象"是一种相当非正式的表达方式.只要您不混淆它所指的内容就可以.

"Current object" is a rather informal way of speaking. It is ok as long as you don't get confused about what it refers to.

不要将其视为一种按时间顺序"的度量 - 当前对象"不是您上次实例化的对象.相反,它是在其上调用方法当前执行的类的实例.

Do not think of it as a kind of "chronological" measure - the "current object" is not the very object you last instantiated anywere. Instead, it is the instance of the class on which you called the current execution of the method.

在撰写this.(...)"时,您不知道 将是哪个实例.现在,当代码被调用时,您将这样做.

At the time of writing "this.(...)", you don't know which instance it will be. You will now when the code is called.

Person somePerson = new Person("Lucy");
somePerson.method();

在这个对 method 的调用中,this"将是 Lucy - 因为方法 method 是在 Person 的特定实例上调用的.您在 method 中创建的小 Person 完全不会影响这一点.

Inside this call to method, "this" will be Lucy - because the method method is being called on that particular instance of Person. The little Persons you create inside method will not affect this at all.

进一步说明:

Person somePerson = new Person("Lucy");
somePerson.method(); // inside method, "this" is Lucy.

Person somePerson = new Person("Anne");
somePerson.method(); // inside method, "this" is Anne.

Person somePerson = new Person("Sarah");
somePerson.method(); // inside method, "this" is Sarah.

Person somePerson = new Person("Emily");
somePerson.method(); // inside method, "this" is Emily.