Reputation: 39
I am learning Javascript on Codecademy. As my understanding Method is a function associated with the objects. I think to call it a method it should inside an object. Is it? Should I really fully understand main difference between functions and methods to write error free code. This is very confusing to me.
Below it the Codecademy code, they say on line 2 'setAge' is a Method where it is clearly looks like a function. It is not even related to any Object yet. Coz it is not even inside of any object.
// 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;
bob.setAge = setAge;
// make susan here, and first give her an age of 25
var susan = new Object();
susan.age = 25;
susan.setAge = setAge;
susan.setAge(35);
// here, update Susan's age to 35 using the method
Upvotes: 2
Views: 1774
Reputation: 23863
As others have said, a method and a function have a lot in common, in fact all methods are functions.
The biggest difference is that a method is attached to an object and the this
value gets set when that object is called.
I've made a snippet to demonstrate
"use strict";
var bob = {
bool: true
};
bob.test = function() {
console.log("this = ", this);
};
console.log("Here is bob test and 'this'");
bob.test();
// Separate the method
var tmp = bob.test;
// In strict mode, this will be undefined.
// In non-strict, it will be the same as `window`
tmp();
Upvotes: 0
Reputation: 3709
That's a good question, I could see how that could be confusing. It appears that they are referring to it as a method because they later modify the bob
object to include the function, thereby making it a "method".
var setAge = function (newAge) {
// using "this" sometimes indicates
// that a function may instead be an object method
this.age = newAge;
};
// becomes a method
bob.setAge = setAge;
Their code is equivalent to the following:
bob.setAge = function (newAge) {
this.age = newAge;
};
You are right in your understanding about methods.
Upvotes: 1