Question about scope and methods


#1


https://www.codecademy.com/en/courses/spencer-sandbox/2/2?curriculum_id=506324b3a7dffd00020bf661

I'm a little confused about scope and methods and I was hoping that someone could clarify. According to this exercise it says that methods (which if I understand correctly are properties that are set as a function) can be used to change the object's other property values. I'm confused because since the other properties are outside of that function's scope, how can the function change/set the value of the object's other properties?

var bob = new Object();
bob.name = "Bob Smith";
// Below this note is the property that's updated by the function 
//which is outside of the function's scope
bob.age = 30;
// Below this note is the function that changes bob.age
bob.setAge = function (newAge){
  bob.age = newAge;
};
bob.setAge(20);


#2

well, we can have a look if the method was successful:

console.log(bob.age);

your object bob has 2 property's: age and name. And one method: setAge. property's defined directly inside the object are accessible by a method.

It might not look as such,, but your setAge method is most certainly part of your object.

Property's defined directly in a object have a global scope inside the object. Just like a normal variable is global and can be edited by functions:

x = 5;
var y = function(x){
  return x + 1
};
x = y(x);
console.log(x);

same for methods, they can edit propertys defined directly inside the object