Can someone provide a simple explanation of methods vs. functions in OOP context?
Here is some explanation for method vs. function using JavaScript examples:
test(20, 50);
is function define and use to run some steps or return something back that can be stored/used somewhere.
You can reuse code: Define the code once and use it many times.
You can use the same code many times with different arguments, to produce different results.
var x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
var test = something.test();
here test() can be a method of some object or custom defined a prototype for inbuilt objects, here is more explanation:
JavaScript methods are the actions that can be performed on objects.
A JavaScript method is a property containing a function definition.
Built-in property/method for strings in javascript:
var message = "Hello world!";
var x = message.toUpperCase();
//Output: HELLO WORLD!
Custom example:
function person(firstName, lastName, age, eyeColor) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.eyeColor = eyeColor;
this.changeName = function (name) {
this.lastName = name;
};
}
something.changeName("SomeName"); //This will change 'something' objject's name to 'SomeName'
You can define properties for String, Array, etc as well for example
String.prototype.distance = function (char) {
var index = this.indexOf(char);
if (index === -1) {
console.log(char + " does not appear in " + this);
} else {
console.log(char + " is " + (this.length - index) + " characters from the end of the string!");
}
};
var something = "ThisIsSomeString"
// now use distance like this, run and check console log
something.distance("m");
Some references: Javascript Object Method, Functions, More info on prototype