15

I'm looking through some code, and I don't quite follow the use of the this keyword in an extension class. It the code shown below, when the objected is instantiated the this kw is used, but when it's being modified or referenced (say for comparison) this is not used.

What's going on here? When do you use this KW when dealing with extension classes?

public class myControllerExtension {

    private final Account acct;

    // The extension constructor initializes the private member
    // variable acct by using the getRecord method from the standard
    // controller.
    public myControllerExtension(ApexPages.StandardController stdController) {
        this.acct = (Account)stdController.getRecord();
        acct.OwnerId = UserInfo.getOwnerId();
    }
17

The keyword this is used to explicitly call out that the code is referencing a member of the object. In some languages it can be left off (and is therefore implicitly implied) and this can be a matter of stylistic preference. Using it indicates that you explicitly want the member belonging to this instance (as opposed to a static, base, or super instance related to your object.)

Most often this is used to differentiate between constructor variables and member variables of the same name (or in other cases where it's ambiguous which variable you're referring to). For example

public class TriggerHelper {
  private List<Opportunity> opptys;

  public TriggerHelper(List<Opportunity> opptys) {
    this.opptys = opptys;
  }
}

For further Reference: Salesforce documentation on the this keyword.

  • so, there was no real need for him to use the this KW in this context? Or equally, he could have added the this KW and it would have had the same effect? – PartOfTheOhana May 2 '13 at 20:12
  • 5
    Yes - in the simple example above, this.acct could have been used everywhere, nowhere, or sometimes and it would have no effect. However, and related to the stylistic preference point above; I personally like to always use this.myvar everywhere so when reading the code, I can easily distinguish between object instance variables versus method variables (which might have closely-related names) – cropredy May 2 '13 at 20:59
  • 4
    to back up what @crop1645 said, I attended a Dreamforce session (@RichUnger and Ryan Spraetz's Apex Puzzlers youtube.com/watch?v=qO5H-W-TL7c) where using this was strongly recommended, one of the reasons is the case insensitivity of apex – Daniel Blackhall May 6 '13 at 0:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.