Why should method be used


On Lesson 13 it says use bob.setAge = function (newAge ){bob.age = newAge;};
We can do by bob.age =20;

Why should we use method, to me it seems extra coding, what is the benefit of it

No error, just a doubt for clarification

// here is bob again, with his usual properties
var bob = new Object();
bob.name = "Bob Smith";
bob.age = 30;
// this time we have added a method, setAge
bob.setAge = function (newAge){
  bob.age = newAge;
// here we set bob's age to 40
// bob's feeling old.  Use our method to set bob's age to 20
// Why not the below line only
bob.age = 20;


in this particular case? Nothing. But sometimes you need to learn certain concepts (overwriting member variable with methods), the easiest way for learners to understand is a simply exercise.

We could put a really complicated example where it is the most efficient way, but i think you will learn less from it.


Your question is a little vague. Methods are functions in objects. Do you mean, what is the benefit of functions, or why would we put a function in an object?

Functions are very useful. They are reusable code, meaning you don't have to rewrite something, which becomes increasingly important the larger your project becomes. For example:

function add(a, b) {
return a + b;
add(1, 2); // returns 3
add(4, 5) // returns 9

Is much tidier than writing the same thing over and over. And if you wanted to change something (like alert the result instead of returning it) you would just change it in one place.

Why would you put a function in an object? Much the same reason you would put anything in an object. It's tidier and less repetitive. For one thing, you can create multiple instances/copies of an object, and they can all have copies of that function/method, rather than writing it out each time. It can also be tidier, and can sometimes give better control of the scope of variables to avoid conflicts. Read an article on scope and the benefits of OOP and it will explain it more.

Admittedly, some of the benefits are more noticeable when you have large projects. If your working on a website that's 500 lines of JavaScript you notice the benefits more than if the project is 50 lines.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.