14/33 objects I : a question!


#1



couldnt we just say:
bob.age = function (newAge) {
blah blah blah... } instead of making a property for age and then a new method for altering the age seperately??im a little bit confused :confused:


// 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.setAge(20);
// bob's feeling old.  Use our method to set bob's age to 20


#2

@radking,
If you would do as you suggested

var bob = new Object();
bob.age = function (newAge){
  bob.age = newAge;
};
console.log(bob);      =output=> { age: [Function] }

bob.age(20);
console.log(bob);      =output=> { age: 20 }

you would have created a self-destructing Method
as bob's age property would change from having an assoicated function Value (Method)
to a property having an associated number Value

( you could use this in a mission-impossible self-destructing story )


#3

One could have a function that returns the value and has an optional parameter for setting it. But that might just as well be two functions like everyone's already used to and since setting and getting are separate actions, they should be separate functions (a getter and a setter)

@radking getters and setters are useful when you want to make certain information available but you might not want to expose your internals. For example, you can represent a point in time as the number of seconds passed since January 1 1970 but still make available which day of the week that is through a property. Later you might decide to count from 1950 instead, but only the internals changed, those who use the class can't tell the difference.


#4

thanks guys that helped!


#5

There is a difference:
If you write:
console.log(bob.setAge); It will give you out put : [Function] indicating you are printing property.

If you write:
console.log(bob.setAge(20)), You are calling the method. So, only when you are calling a method the method will work and change the age.

So, there is a difference between calling a method console.log(bob.setAge(20)) and just printing the property console.log(bob.setAge).

Only if you call the method that can change the other property.

Sorry I just realised I put a console.log() around the method that is unnecessary/not correct. just bob.setAge(20); will call the method.