Use of this in Delphi

Asked

Viewed 142 times

0

So as there is this in Javascript, what is the equivalent in Delphi? And how would I use it? I want to replace the 'Unibuttonx' of each procedure with a 'this' equivalent to the button clicked.

procedure TUniForm1.UniButton1Click(Sender: TObject);
var numero : string;
begin
   numero := UniEdit1.Text;
   UniEdit1.Text := numero + UniButton1.Caption;
end;

procedure TUniForm1.UniButton2Click(Sender: TObject);
var numero : string;
begin
   numero := UniEdit1.Text;
   UniEdit1.Text := numero + UniButton2.Caption;
end;
  • The this of Delphi is called self. But in the case in question it refers to the form, since all methods are from Tuniform1. As you saw yourself, the button comes from the Sender parameter.

1 answer

1


Got it... it’s the 'Sender'.

procedure TUniForm1.UniButton1Click(Sender: TObject);
var numero : string;
begin
   numero := UniEdit1.Text;
   UniEdit1.Text := numero + TUniButton(sender).Caption;
end;

procedure TUniForm1.UniButton2Click(Sender: TObject);
var numero : string;
begin
   numero := UniEdit1.Text;
   UniEdit1.Text := numero + TUniButton(sender).Caption;
end;

However I still have the doubt of how I could create a function for when calling it in the Onclick of each button, run it with the 'Sender' of the button clicked.

I did it again...

procedure TUniForm1.clique(Sender: TObject);
var numero : string;
begin
   numero := UniEdit1.Text;
   UniEdit1.Text := numero + TUniButton(sender).Caption;
end;

procedure TUniForm1.UniButton1Click(Sender: TObject);
begin
   clique(TUniButton(sender));
end;

procedure TUniForm1.UniButton2Click(Sender: TObject);
begin
   clique(TUniButton(sender));
end;

If anyone has any code optimization suggestions, please reply/comment. What I am doing is a calculator in Delphi.

  • 1

    It is possible to use the same method for event of more than one button, this would avoid having a Unibuttonclick for each button.

  • True! I had forgotten that. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.