Part 5: Why do we need "this."?


#1

My code works, but I'm not sure why "this." is needed:

var cashRegister = {
total:0,
lastTransationAmount: 0,
add: function(itemCost) {
this.total += itemCost;
this.lastTransationAmount = itemCost;

It would help me to know! Thanks!


#2

== the Book ==
javascript this site:developer.mozilla.org
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
== discussions / opinions ==
javascript this explained site:stackoverflow.com
= http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work

The code

var cashRegister = {
 total:0,
 lastTransationAmount: 0,
 add: function(itemCost) {
this.total += itemCost;
this.lastTransationAmount = itemCost;

could have been written as

var cashRegister = {
   total:0,
   lastTransationAmount: 0,
   add: function(itemCost) {
           //itemCost is a PARAMETER of =anonymous Function=
           // itemCost is used as =local= VARIABLE
           //ARGUMENT used should be a =number VALUE=
           // throughout FUNCTION-BODY
           cashRegister.total += itemCost;
           cashRegister.lastTransationAmount = itemCost;
   }, .....
};

some quotes from the outer-world:

argument is the value/variable/reference being passed in,
parameter is the receiving variable used within the function/block

OR

**"parameters" are called "formal parameters",
while "arguments" are called "actual parameters".**


#3

this is for "this" object that you are in and not some outside object. In this case you are talking about the cashRegister object your method "add" is part of.