What is a difference between a method and a function?

后端 未结 7 1414
礼貌的吻别
礼貌的吻别 2020-12-08 00:15

What is the difference between a method and a function? Is it that a method returns a value and a function doesn\'t?

相关标签:
7条回答
  • 2020-12-08 00:32

    In one line, a method is a function but a function is not necessarily a method. The difference is that a method is used to describe functions defined in classes that are used with instances of those classes.

    package {class Example {
      public function iAmAMethod():void {
         addEventListener("listenerFunctionIsNotAMethod", function(event:Event):void {
            trace("inline function, yay!");
         });
      }
    

    }

    0 讨论(0)
  • 2020-12-08 00:36

    Both are used interchangeably, but function is the terminology used in structural languages and method is the terminology used in Object Oriented Langauages. Also methods exists within objects while functions can exist without objects as well.

    0 讨论(0)
  • 2020-12-08 00:43

    Method is actually a function used in the context of a class/object.

    When you create a function outside of a class/object, you can call it a function but when you create a function inside a class, you can call it a method.

    class foo {
       public function bar() { // a method
         ........
       }
    }
    

    function bar() {  // a function not part of an object
    }
    

    So an object can have methods (functions) and properties (variables).

    0 讨论(0)
  • 2020-12-08 00:46

    The difference between the expressions "method" and "function" is that a "method" is a member function of a class, whereas a standalone function does not, and a standalone function usually exists in global context.

    0 讨论(0)
  • 2020-12-08 00:50

    The words are not opposed to each other but rather describes two possible aspects of a subroutine. An attempt to define the words follows:

    Subroutine: A set of instructions that can be used several times in the same program.

    Function: A subroutine that returns a value. Derived from functions in mathematics (wikipedia).

    Method: A subroutine that belongs to an object or a class. Could be a function.

    I tend to use the word "function" for every subroutine that has no side effects but returns one clear value and the word "method" for every subroutine that has a side effect.

    0 讨论(0)
  • 2020-12-08 00:50

    Function is a generic term to be used in procedural programming approach where as Method is a term to be used in Object oriented programming approach to define a class property.

    0 讨论(0)
提交回复
热议问题