What's the difference between a method and a function?

前端 未结 30 3392
粉色の甜心
粉色の甜心 2020-11-21 05:08

Can someone provide a simple explanation of methods vs. functions in OOP context?

30条回答
  •  星月不相逢
    2020-11-21 05:50

    A function is a mathematical concept. For example:

    f(x,y) = sin(x) + cos(y)
    

    says that function f() will return the sin of the first parameter added to the cosine of the second parameter. It's just math. As it happens sin() and cos() are also functions. A function has another property: all calls to a function with the same parameters, should return the same result.

    A method, on the other hand, is a function that is related to an object in an object-oriented language. It has one implicit parameter: the object being acted upon (and it's state).

    So, if you have an object Z with a method g(x), you might see the following:

    Z.g(x) = sin(x) + cos(Z.y)
    

    In this case, the parameter x is passed in, the same as in the function example earlier. However, the parameter to cos() is a value that lives inside the object Z. Z and the data that lives inside it (Z.y) are implicit parameters to Z's g() method.

提交回复
热议问题