`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 =
  object
    val name : string = name
    method say_hello = print_endline ("Hello I am " ^ name)
    method get_name = name
  end

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

let () =
  let anji = new person "Anji" in
  anji#say_hello;
  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).

Cheers,
Nicolas

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)
  end

class say_hello name =
  object
    inherit base_say_hello
    method get_name = name
  end

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

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