-3

For instance, consider the code snippet :

var john=
{  fullname: 'john smith',
  bill:[124,48,268,180,42],
  tip:[],final:[],
  calcTip:function()
  {
    for(var i =0;i<this.bill.length;i++)
    {
      if(this.bill[i]<50)
      this.tip[i]=0.2*this.bill[i];
      else
      this.tip[i]=0.1*this.bill[i];
      this.final[i]=this.tip[i]+this.bill[i];
    }
  }
};

I tried skipping the usage of 'this' to access array members of bill and this was the output that it produced :


Uncaught ReferenceError: bill is not defined

  • 1
    How are you calling the function? `john.calcTip()` works fine – adiga Jun 28 '20 at 12:15
  • 1
    If you want to use any object key-values inside the function defined in same object you need it access from this keyword because here this hold the whole context of that object. – Parse Shyam Jun 28 '20 at 12:20
  • The error is not reproducible with the code you’ve shared. Please, [edit] your question and provide a [mre]. – Sebastian Simon Jun 28 '20 at 12:21

1 Answers1

0

If you call the function like john.calcTip() then JavaScript replaces this with the value stored in john inside the function calcTip. Basically any value before the . attached to a function call is the value of this inside the function.

If you do not want to use this inside the function calcTip you can replace this with john like:

var john=
 {  fullname: 'john smith',
  bill:[124,48,268,180,42],
  tip:[],final:[],
  calcTip:function()
  {
    for(var i =0;i<john.bill.length;i++)
    {
     if(john.bill[i]<50)
     john.tip[i]=0.2*john.bill[i];
     else
     john.tip[i]=0.1*john.bill[i];
    john.final[i]=john.tip[i]+john.bill[i];
    }
  }

};

Ogie
  • 1,304
  • 2
  • 14
  • 17