Try  HackMD Logo HackMD

Q: difference between function and method ?

the difference between a method and a function is that a method is just a function that lives inside of an object.

//function
function show(value) {
// task perform
}

// method
const user = {
show: function() {
// task perform
}
}

show() // function

user.show() // method

Function is independent. and method depend on function object.
or
A method is a piece of code that is called by a name that is associated with an object
another example:

const wes ={
name: "wes",
propertyToCheck: "NEVER",
age,
"cool-dude": true,
"really cool": false,
"777": true,
dog: "snickers",
clothing: {
shirts: 10,
pants: 2
},
sayHello: function(greeting = "Hey") {
return ${greeting} ${this.name};
}
};

wes.sayHello()
output: "Hey Wes"

You can also try passing in a greeting as shown below, which would return "Hello wes".

wes.sayHello('Hello');
output: "Hello wes"

There also is a method shorthand that consist of taking the function keyword away and without colon like this

const wes ={
name: "wes",
propertyToCheck: "NEVER",
age,
"cool-dude": true,
"really cool": false,
"777": true,
dog: "snickers",
clothing: {
shirts: 10,
pants: 2
},
sayHello(greeting = "Hey") {
return ${greeting} ${this.name};
}
};

However, you can add arrow functions.

const wes ={
name: "wes",
propertyToCheck: "NEVER",
age,
"cool-dude": true,
"really cool": false,
"777": true,
dog: "snickers",
clothing: {
shirts: 10,
pants: 2
},
sayHello(greeting = "Hey") {
return ${greeting} ${this.name};
},
sneeze: () => {
console.log("AHHHH CHOOO");
}
};
That is still a method, however because it is an arrow function as a property on an object, we do not have access to the this keyword.