`self` use case?

Hello! Documentation says

...In fact this names the object, allowing you to call methods in the same class or pass the object to functions outside the class. In other words, it's exactly the same as this in C++/Java. ...

I did not understand this because it seems like I can just pass the object whenever I want to an outside function like this:

class person name =
    val name : string = name
    method say_hello = print_endline ("Hello I am " ^ name)
    method get_name = name

let make_say (p : person) (s : string) =
  print_endline (p#get_name ^ " said: " ^ s)

let () =
  let anji = new person "Anji" in
  make_say anji "I'll give you money!"

The output was

Hello I am Anji
Anji said: I'll give you money!

You need ‘self’ a.k.a. ‘this’ to call one method from another one.

1 Like

It means that it allows passing the current object from within the body of one of its methods; of course, if you are “outside” the object you can pass it around (as in your example).


1 Like

It’s most useful with inheritance.

class virtual base_say_hello =
  object (self)
    method virtual get_name : string
    method say_hello = print_endline ("Hello I am " ^ self#get_name)

class say_hello name =
    inherit base_say_hello
    method get_name = name

let () = (new say_hello "Anji")#say_hello
1 Like

Ah I see, thanks guys :smiling_face_with_three_hearts: :innocent: