17/19 "This" Works for Everyone... except me. (No coding problem. I just don't understand the point!)


#1

I don't understand the point of using this.blahblah.

Instead of bob,age = (new age), I create a function with 3 or 4 additional lines of code. Then I ignore that code by declaring bob.age = newAge... then I type bob.newAge = number.

Why?

What is the purpose of this coding when I could have written bob.age = number.

I assume that there is a point but I don't see it.

Any explanation would be great.

Thanks in advance.
Dr. K


#2

The this. keyword applies to the object in which you're using it. So as you write your function:

var setAge = function(newAge){
    this.age = newAge;
}

the this. would be a reference to one of the global objects (window or document, I guess, not really that important here) but it would so far have no connection to your bob object. Now when you connect this function to a property of bob by:


bob.setAge = setAge;

Now the function is part of bob, so now the this. as well will refer to bob. So if you use bob.setAge(10) it will change the age property of bob.

But you're somehow right as well as it doesn't make much sense to do it this way because you could just do this directly by using bob.age = newAge. The point where these so-called setter methods get important is when you get to know private properties of objects. These are informations that are part of the object but are invisible to the outside world, for example because you want to restrict the access for them. Therefore you need to write simple function like these setters or getters, that do nothing else but return or replace a value, to see or modify these information.
So although they are of little use now you might see them again one day.


#3

Thanks Haxor789 for the for the clear explanation.

I was starting to think it was a "not now but later" script, which was confirmed as I moved to some later lessons.

Sort of a "Hodor. Hodor." moment!

Dr. K


#4

Was that a Hodor time travel reference without a spoiler alert!? Shame. Shame. Shame. :smiley:


#5

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