0

I'm trying to get this piece of code to work, but can't figure out why myInvoice.amount is evaluating to NaN.

I initially thought it had something to do with the value of this, but if that were the case, why is myInvoice.total() working correctly?

function createInvoice(services = {}) {
  return {
    phone: services['phone'] || 3000,
    internet: services['internet'] || 5500,
    amount: (this.phone + this.internet),

    total() {
      return this.phone + this.internet;
    },

  };
}

let myInvoice = createInvoice(); 
console.log(myInvoice.phone); // 3000
console.log(myInvoice.internet); // 5500
console.log(myInvoice.amount); // NaN
console.log(myInvoice.total()); // //8500

I've also checked the typeof phone and internet and they're both numbers. I've also included what gets logged to the console in a comment next to the expression.

Any help would be appreciated!

Thanks

bugsyb
  • 5,662
  • 7
  • 31
  • 47
  • 2
    The value of `this` is determined by how the function it appears within is called; it is completely unrelated to any nearby object literal. – Quentin Apr 22 '21 at 17:35
  • When calling `createInvoice()`, `this` will be set to the global object `window` or `null` if your script is evaluated in strict mode. `this.phone + this.internet` -> `window.phone + window.internet` -> `undefined + undefined` -> `NaN` assuming that both those global properties are not set and you are not in strict mode. If you want to refer to the object you are building store it in a variable first. `const invoice = { ... }`, then `invoice.amount = invoice.phone + invoice.internet` and `return invoice` – 3limin4t0r Apr 22 '21 at 17:49

0 Answers0