Method vs Functions, and other questions

52,065

Solution 1

To answer your title question as to what is the difference between a 'function' and a 'method'.

It's semantics and has to do with what you are trying to express.

In JavaScript every function is an object. An object is a collection of key:value pairs. If a value is a primitive (number, string, boolean), or another object, the value is considered a property. If a value is a function, it is called a 'method'.

Within the scope of an object, a function is referred to as a method of that object. It is invoked from the object namespace MyObj.theMethod(). Since we said that a function is an object, a function within a function can be considered a method of that function.

You could say things like “I am going to use the save method of my object.” And "This save method accepts a function as a parameter.” But you generally wouldn't say that a function accepts a method as a parameter.

Btw, the book JavaScript Patterns by Stoyan Stefanov covers your questions in detail, and I highly recommend it if you really want to understand the language. Here's a quote from the book on this subject:

So it could happen that a function A, being an object, has properties and methods, one of which happens to be another function B. Then B can accept a function C as an argument and, when executed, can return another function D.

Solution 2

There is a slight difference -

Method : Method is a function when object is associated with it.

var obj = {
name : "John snow",
work : function someFun(paramA, paramB) {
    // some code..
}

Function : When no object is associated with it , it comes to function.

function fun(param1, param2){
// some code...
}

Solution 3

Many answers are saying something along the lines that a method is what a function is called when it is defined on an object.

While this is often true in the way the word is used when people talk about JavaScript or object oriented programming in general (see here), it is worth noting that in ES6 the term method has taken on a very specific meaning (see section 14.3 Method Definitions of the specs).


Method Definitions

A method (in the strict sense) is a function that was defined through the concise method syntax in an object literal or as a class method in a class declaration / expression:

// In object literals:
const obj = {
    method() {}
};

// In class declarations:
class MyClass {
    method() {}
}

Method Specificities

This answer gives a good overview about the specificities of methods (in the strict sense), namely:

  1. methods get assigned an internal [[HomeObject]] property which allows them to use super.
  2. methods are not created with a prototype property and they don't have an internal [[Construct]] method which means that they cannot be called with new.
  3. the name of a method does not become a binding in the method's scope.

Below are some examples illustrating how methods (in the strict sense) differ from functions defined on objects through function expressions:

Example 1

const obj = {
    method() {
        super.test;         // All good!
    },
    ordinaryFunction: function ordinaryFunction() {
        super.test;         // SyntaxError: 'super' keyword unexpected here
    }
};

Example 2

const obj = {
    method() {},
    ordinaryFunction: function ordinaryFunction() {}
};

console.log( obj.ordinaryFunction.hasOwnProperty( 'prototype' ) );  // true
console.log( obj.method.hasOwnProperty( 'prototype' ) );            // false

new obj.ordinaryFunction();     // All good !
new obj.method();               // TypeError: obj.method is not a constructor

Example 3

const obj = {
    method() {
        console.log( method );
    },
    ordinaryFunction: function ordinaryFunction() {
        console.log( ordinaryFunction );
    }
};

obj.ordinaryFunction()  // All good!
obj.method()            // ReferenceError: method is not defined

Solution 4

A method is a property of an object whose value is a function. Methods are called on objects in the following format: object.method().

//this is an object named developer

 const developer = {
  name: 'Andrew',
  sayHello: function () {
    console.log('Hi there!');
  },
  favoriteLanguage: function (language) {
    console.log(`My favorite programming language is ${language}`);
  }
};

// favoriteLanguage: and sayHello: and name: all of them are proprieties in the object named developer

now lets say you needed to call favoriteLanguage propriety witch is a function inside the object..

you call it this way

developer.favoriteLanguage('JavaScript');

// My favorite programming language is JavaScript'

so what we name this: developer.favoriteLanguage('JavaScript'); its not a function its not an object? what it is? its a method

Solution 5

A function executes a list of statements example:

 function add() { 
     var a = 2; 
     var b = 3;
     var c = a + b;
     return c;
 }

1) A method is a function that is applied to an object example:

 var message = "Hello world!";
 var x = message.toUpperCase(); // .toUpperCase() is a built in function

2) Creating a method using an object constructor. Once the method belongs to the object you can apply it to that object. example:

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
    this.name = function() {return this.firstName + " " + this.lastName;};
}

document.getElementById("demo").innerHTML = person.fullName(); // using the 
method 

Definition of a method: A method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object.

Share:
52,065
Karan Goel
Author by

Karan Goel

Updated on July 09, 2022

Comments

  • Karan Goel
    Karan Goel almost 2 years

    With respect to JS, what's the difference between the two? I know methods are associated with objects, but am confused what's the purpose of functions? How does the syntax of each of them differ?

    Also, what's the difference between these 2 syntax'es:

    var myFirstFunc = function(param) {
        //Do something
    };
    

    and

    function myFirstFunc(param) {
        //Do something
    };
    

    Also, I saw somewhere that we need to do something like this before using a function:

    obj.myFirstFunc = myFirstFunc;
    obj.myFirstFunc("param");
    

    Why is the first line required, and what does it do?

    Sorry if these are basic questions, but I'm starting with JS and am confused.

    EDIT: For the last bit of code, this is what I'm talking about:

    // here we define our method using "this", before we even introduce bob
    var setAge = function (newAge) {
      this.age = newAge;
    };
    // now we make bob
    var bob = new Object();
    bob.age = 30;
    // and down here we just use the method we already made
    bob.setAge = setAge;
    
  • RobG
    RobG about 11 years
    Not my downvote, but likely because the first is a FunctionExpression, the second is a FunctionDeclaration, the difference is when they are created. The first is when that line of code is executed, the second is created before any code is executed.
  • Dave
    Dave about 11 years
    @user2059238: I can't think of a simple good reason, but it could be needed in a library function which has a callback (the function can be passed as a parameter), or if you have two possible behaviours to choose between (obj.doYourThing = isAngel ? myGoodFunc : myBadFunc), although the second is rather silly. It also lets you define private functions which are also public if you're using closures (but that only gives any benefit if you're also using an optimising compiler).
  • Dave
    Dave about 11 years
    yes, because you need to set it to something! My point is that you should use bob.setAge = function(){whatever} rather than function blah(){whatever};bob.setAge=blah;. The latter is bad because it pollutes the scope with variables, and leaves a function which only makes sense when applied to an object (and if you used this in the function, is only safe when applied to an object)
  • Karan Goel
    Karan Goel about 11 years
    That actually helps. I'll look up more on this and ask further if I have doubts
  • Nicholas
    Nicholas almost 8 years
    You comment that it cannot be passed as a parameter is not true.
  • Tina Chen
    Tina Chen almost 6 years
    According to this answer, just saying If a value is a function, it is called a 'method'. seems not accurate?
  • mastaBlasta
    mastaBlasta almost 6 years
    @TinaChen you are right this answer reflects the state of javascript in 2013 and needs to be updated for ES6. Frankly the whole thing is not that important. Call it whatever you want: function/method. A function is usually in the top level (global) namespace, a method belongs to a class/object namespace and has to be called with that receiver.
  • elin
    elin over 5 years
    primitive is number, string, boolean
  • forresthopkinsa
    forresthopkinsa almost 5 years
    Excellent modern answer
  • Mike
    Mike almost 3 years
    Great, simple answer.