Method vs Functions, and other questions

JavascriptFunctionMethods

Javascript Problem Overview


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;

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

Your first line, is creating an object that references a function. You would reference it like this:

myFirstFunc(param);

But you can pass it to another function since it will return the function like so:

function mySecondFunction(func_param){}
mySecondFunction(myFirstFunc);

The second line just creates a function called myFirstFunc which would be referenced like this:

myFirstFunc(param);

And is limited in scope depending on where it is declared, if it is declared outside of any other function it belongs to the global scope. However you can declare a function inside another function. The scope of that function is then limited to the function its declared inside of.

function functionOne(){
    function functionTwo(){}; //only accessed via the functionOne scope!
}

Your final examples are creating instances of functions that are then referenced though an object parameter. So this:

function myFirstFunc(param){};

obj.myFirst = myFirstFunc(); //not right!
obj.myFirst = new myFirstFunc(); //right!

obj.myFirst('something here'); //now calling the function

Says that you have an object that references an instance of a function. The key here is that if the function changes the reference you stored in obj.myFirst will not be changed.

While @kevin is basically right there is only functions in JS you can create functions that are much more like methods then functions, take this for example:

function player(){
    
    this.stats = {
        health: 0,
        mana: 0,

        get : function(){
            return this;
        },

        set : function( stats ){
            this.health = stats.health;
            this.mana = stats.mana;
        }  
}    

You could then call player.stats.get() and it would return to you the value of heath, and mana. So I would consider get and set in this instance to be methods of the player.stats object.

Solution 5 - Javascript

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.

Solution 6 - Javascript

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 7 - Javascript

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

and

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

are (almost) identical. The second is (usually) just shorthand. However, as this jsfiddle (http://jsfiddle.net/cu2Sy/) shows, function myFirstFunc will cause the function to be defined as soon as the enclosing scope is entered, whereas myFirstFunc = function will only create it once execution reaches that line.

As for methods, they have a this argument, which is the current object, so:

var obj = {};
obj.func = function( ) {
    // here, "this" is obj
    this.test = 2;
}
console.log( obj.test ); // undefined
obj.func( );
console.log( obj.test ); // 2

The exact syntax you showed is because you can also do this:

function abc( ) {
    this.test = 2;
}
var obj = {};
obj.func = abc;
obj.func( ); // sets obj.test to 2

but you shouldn't without good reason.

Solution 8 - Javascript

ecma document

> 4.3.31method : > function that is the value of a property > > NOTE When a function is called as a method of an object, the object is > passed to the function as its this value.

It is very clear: when you call a function if it implicitly has a this (to point an object) and if you can't call the function without an object, the function deserves to name as method.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKaran GoelView Question on Stackoverflow
Solution 1 - JavascriptmastaBlastaView Answer on Stackoverflow
Solution 2 - JavascriptPushpendra SinghView Answer on Stackoverflow
Solution 3 - JavascriptOliver SiewekeView Answer on Stackoverflow
Solution 4 - JavascriptRyanView Answer on Stackoverflow
Solution 5 - JavascriptticktockView Answer on Stackoverflow
Solution 6 - JavascriptRidha RezzagView Answer on Stackoverflow
Solution 7 - JavascriptDaveView Answer on Stackoverflow
Solution 8 - Javascriptmustafa kemal tunaView Answer on Stackoverflow