Functions and Methods... What is the REAL difference?


#1

Ok I'm doing some review on objects before I move on to other programming language (C# so excited :smile:).

The lesson says:

Methods serve several important purposes when it comes to objects.

They can be used to change object property values.

and it says:

They can be used to make calculations based on object properties. Functions can only use parameters as an input, but methods can make calculations with object properties.

So I modified the code in the example to see if i could "change object property values" with a function defined with the var keyword.and to see if I could "make calculations with object properties" In the following code I was able to do both:

var bob = new Object();
bob.age = 17;
// this time we have added a method, setAge
var setAge = function (newAge){
  bob.age = newAge;
};
setAge(40);
var  getYearOfBirth = function () {
  return 2014 - bob.age;
};
console.log(getYearOfBirth());
console.log(bob.age);

Is there something I am misinterpreting? If not what is the true difference between methods and functions. Please give me an example of something a method can do that a function can not and vise versa.


15. Why are methods important? Do Objects have global scopes? Idk if that questionn makes sense
#2

Hello will,
A method is a function, just as a property is a variable, and just as a variable is an array when it has a string.

However it's the scope that's important. A method is a function assigned to an object. You may easily alter other properties within an objects scope. When working with an object, they become necessary rather than building external functions to reach into objects, and methods to reach out of objects.

You wouldn't make an object to assign event handlers to a Web page, but you make make an object that holds various methods which target different elements to assign event handlers and can be called easily that way.

When looking at Javascript code, many items are complex variations of very consistent and fundamental basics.

I hope this helps or cotributes to your question and understanding. : )