0

enter image description here

I Was Learning the OOP Javascript tutorial and the instructor used the same code I wrote and the output in the first print in console was you have discount and in the second one was you don't have discount while when I use it it prints you don't have discount in the both prints in console

note : the video I have watched have been published 2 years ago so I think that there are some updates that occured to this keyword in javascript which I don't know

I tried this code and it prints you don't have discount in both cases

let obj = {
hasDiscount: true,
showMsg: () => `You${this.hasDiscount ? '' : " Don't"} Have Discount`
}

console.log(obj.showMsg())

let newOne = Object.create(obj);

newOne.hasDiscount = false;

console.log(newOne.showMsg())
  • 2
    i mean... are you sure that's the code from the tutorial? or did you "update" it with what you thought was more modern practices – Kevin B May 12 '23 at 21:54
  • Can you maybe link the tutorial? – David Krell May 12 '23 at 21:56
  • "*I think that there [were] some updates that [occurred] to `this` keyword...*" - updates to JavaScript don't break existing functionality (at least they're intended not to, and I can't personally think of examples where updates *have* broken existing functionality). – David Thomas May 12 '23 at 21:58
  • 2
    [This question is particularly relevant](https://stackoverflow.com/questions/28371982/what-does-this-refer-to-in-arrow-functions-in-es6) to the mistake that was introduced with the updates you likely made to the code. Arrow functions aren't a replacement to regular functions, they actually serve a purpose and won't work in every scenario 1:1. – Kevin B May 12 '23 at 21:59
  • @KevinB you're right I have updated the code with the regular function not the arrow function and it worked well as same as the instructor is this scenario one of the very rare scenarios that occur in specific case like that in arrow function or there are many scenarios that make diffrences between arrow function and regular function – Yassen Mohamed May 12 '23 at 22:10
  • The primary case is: if your function needs access to `this`, you need to be careful with it because arrow functions change how `this` works. In some cases for the better, and in others like yours, it won't work. A lot of modern code avoids using `this` entirely and just never runs into this problem. – Kevin B May 12 '23 at 22:11
  • @KevinB Ok Thanks alot the post you have attached helped me understanding how this work in arrow functions it – Yassen Mohamed May 12 '23 at 22:14

0 Answers0