16

What is the specification of the 'this' keyword in Solidity? How does it work?

Sample code from Solidity Features · ethereum/wiki Wiki

contract Helper {
  function getBalance() returns (uint bal) {
    return this.balance; // balance is "inherited" from the address type
  }
}
19

According to this guide:

Contracts Inherit all Members from Address.

It means that this is the pointer to the current instance of the type derived from Address (in your case - current instance of Helper), and balance is a member of Address.

It helps you distinguish between contract's own balance and any other balance, like in this example:

address x = 0x123;
if (x.balance < this.balance) 
    x.send(10);

And here is a some kind of definition (from this doc):

this: the current contract, explicitly convertible to address

  • 4
    why is this necessary? Can't someone just say if(x.balance < balance)? – Jossie Calderon Jun 15 '17 at 4:04
  • 1
    this (current contract’s type): the current contract, explicitly convertible to Address. This is from the solidity docs. Which means that if you want to access members of the address type (e.g. balance) of the current contract instance, then you can simply use this. In your example, balance will try to access a variable from the contract's storage (i.e. contract public property) – ppoliani Dec 19 '17 at 15:18
  • 2
    this.balance is deprecated, the correct way to get the balance of the contracts is through address(this).balance – Eduardo Pereira Jun 30 '18 at 12:50
4

Contract types are implicitly convertible to address and every contract inherits all members of "address" and overwrites them if necessary. If they are overwritten, the members of address can still be accessed via conversion to address:

address(myContract).send(10). 

This also has the effect that all members of address can be accessed without prefix, i.e. uint x = this.balance; // access the balance parameter of the current contract.

so to summarize "This" represents the current contract instance.

  • 1
    sometimes I see in ERC20 contracts balanceOf(this) – rstormsf Jun 22 '17 at 0:48
  • balanceOf(this) is just a function to get the balance of ERC20 token for the currrent contract, however address(this).balance is the balance of Ether for a current contract. – Eduardo Pereira Jun 30 '18 at 12:48

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.