What is Method, Property and Function?

后端 未结 6 1356
失恋的感觉
失恋的感觉 2021-01-02 08:48

Yeah, I\'m struggling with that. I cannot distinguish among them because every explanation I read is so unclear and philosophical enough. Can someone clear up these definiti

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-02 09:20

    Function is a combination of instructions coupled together to achieve some result. It may take arguments and return result. If a function doesn't return a result it is usually called a procedure. Examples:

    function drawLine(x1, y1, x2, y2):
      // draws a line using Bresenham's algorithm from x1,y1 to x2,y2.
      // doesn't return anything
    
    function  add(a, b):
      // adds a to b and returns the result as a number
      return a + b
    

    So functions are to do some particular work. For example, when you need to draw a polygon of 3 lines as a part of a vector image it is more convenient to call drawLine thrice than to put all the routine for line drawing inline.

    Methods ("member functions") are similar to functions, they belongs to classes or objects and usually expresses the verbs of the objects/class. For example, an object of type Window usually would have methods open and close which do corresponding operations to the object they belong.

    Properties are as in everyday language and technically are fields of objects/classes with dedicated getter/setter routines (which can be considered as methods. There are languages that don't have properties and this behavior is achieved using a private field+get/set methods.).

提交回复
热议问题