17. Some questions about "This"


So why do we have to write like in this example
susan.age = 25;
susan.setAge = setAge;
Why we have to write:
susan.setAge = setAge; ? That way it applies setAge method to this object? And only after that we can give this object property new value (new age)? So now my method is named:
var setAge = function (newAge) {
this.age = newAge; but if its name would be let's say "applyNew" insted of "setAge" then we would have to write code like this?
var susan = new Object();
susan.age = 25;
susan.applyNew = applyNew;

Thanks for helping. Just want to make it all clear.


Well it's a matter a preference actually.

Using the different Object Notation can clear up sections of your code, so group your code in the object as a baseline, and then you can add more later if need be.

So let's say in this example (immediately below) that we only want to make the object, and then later add values and variables to it. We can just initiate the object like so

var example = new Object();

example.variable = "value";

Now in this next example (immediately below) It's similar, except you can choose to leave it open or immediately fill it with properties using the bracket notation:

var example2 = {
    variable: "value",
    variable2: "value2"

After you've made an object you can then modify it's variables since all of the objects variables are "Public" meaning open to the rest of your code.

However, you'd use this. in functions (see example immediately below), or other parts of the Object to relate to the object directly from within itself. So even functions inside of the objects aren't allowed to just use the variables that the Object has inside of it. That's why you'll use the this.variable statement to call those variables.

function Object(sayHello, isHappy) {
    this.sayHello = sayHello;
    this.isHappy = isHappy;
var example3 = new Object("Hello", true);

So it would create the object "example3" using the method "function Object".

I know this is all quite confusing so if you would like me to go into depth on anything please let me know and I'll try my best to help you out!


Thanks, very cleary explained, but I still don't understand why we have to write:
susan.setAge = setAge; before writing susan.setAge(35);


Well that's a little complicated so I'll show you what the console sees.

susan.variable = function;

var function = function ( 35 ) {
this.variable = 35;

I don't know if that explains it for you but I hope it does


I'm a bit late, but yes that helps. If I'm right, that calls the function for the object susan, right?


Technically, it calls a value and stores the return value in the object "susan" but you could say that yes.