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

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

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

30条回答
  •  情话喂你
    2020-11-21 05:34

    TL;DR

    A Function is a piece of code to run.
    A Method is a Function inside an Object.

    Example of a function:

    
    function sum(){
      console.log("sum")l
    }
    

    Example of a Method:

    const obj = {
    a:1,
    b:2,
    sum(){
      }
    }
    

    So thats why we say that a "this" keyword inside a Function is not very useful unless we use it with call, apply or bind .. because call, apply, bind will call that function as a method inside object ==> basically it converts function to method

提交回复
热议问题