method vs function
Monkey Forums/Monkey Beginners/method vs function
| ||
what is the purpose of a method if its just like a function and what does "self" do pls help. |
| ||
Methods are used with an instance of a class, whereas Functions are used with the class itself. http://www.monkeycoder.co.nz/docs/html/Programming_Language%20reference.html#functions http://www.monkeycoder.co.nz/docs/html/Programming_Language%20reference.html#methods "Self" is a reference to the current object, the object which method is currently being called. Heres a simple example: Class Foo Field x:Float ' constructor Method New(x:Float) Self.x = x End Method GetX:Float() Return Self.x End Method SetX:Void(x:Float) Self.x = x End Function CreateFoo:Foo(x:Float) Local f:Foo = New Foo(x) Return f End End Function Main:Int() Local f:Foo = New Foo(10) Local tmpX:Float = f.GetX() Local newFoo:Foo = Foo.CreateFoo(20) Return True End |
| ||
I do believe invaderJim's tutorials go over this: http://www.monkeycoder.co.nz/Community/posts.php?topic=3318&page=1 | From the index anyways, it looks like it'll explain this. |
| ||
This http://stackoverflow.com/a/155655 is possibly the best explanation of the difference between a function and a method. As therevills says, "Self" is a reference to the current object, the object which method is currently being called Think of Self as special variable in an objects instance to it's own location in memory. NOTE: if you tried to use Self within the CreateFoo function, it will not compile and give you the error, "illegal use of Self within static scope" even though CreateFoo is within the class Foo, it is not part of an object instance. You could have had Function CreateFoo out side of the class, but I wouldn't recommend it for creating object instances. Functions outside of a class to me should be general purpose. Like wise you should never pass Self as a parameter to a function or method within a constructor (Method New()) as the object wouldn't exist until after then constructor has exited; it will just crash with an access violation. |
| ||
appreciate the help guys, you all get a star! :)~ |
| ||
The basic idea of object orientation is that you have an object (a chunk of data) combined with a collection of operations that work on the data. A method is such an operation which is automatically bound to a single instance of its class. Consider the following example: The GetArea() method and function are functionally the same. But the method doesn't need to be told which rectangle to use (or at least it is told in a different way), and also it is nicely tidied away within the class scope. At the lowest level of compiled code, both method and function will probably wind up exactly the same. |