0

I am taking the PluralSight course for ES6 Rapid Learning. And I came down to object-literal extensions in ES6. So in the video it is said that the outcome of the below code will NOT refer to the price in the productView object. Yet my Chrome console shows 150, not 12.

If someone can explain this, I will be very thankful.

'use strict';
let price = 6.00,
    quantity = 2;

let productView = {
    price: 15,
    quantity: 10,
    calculateValue() {
        return this.price * this.quantity;
    }
};
console.log(productView.calculateValue());
Niladri
  • 5,832
  • 2
  • 23
  • 41
  • `this.price` refers to the `price: 15,` property in `productView` object , hence you got 150 when you call `calculateValue()` – Niladri Jun 02 '18 at 15:05
  • Well the mentor says and I quote: "When we use this function within an Object Literal, this is going to refer to the context of the code." And his console is showing 12... – Bogdan Lozev Jun 02 '18 at 15:09
  • if you use an arrow function which does not create any scope of it's own then it will return 12 as it will take the value of the variables declared outside the object literal . For example `calculateValue: () => price * quantity` . You can run it in http://babeljs.io/ – Niladri Jun 02 '18 at 15:15
  • Thank you very much. I've tried it. But still I can't realize why the same code (copy and paste) in the course-video, which the mentor is writing shows 12. – Bogdan Lozev Jun 02 '18 at 15:18
  • @BogdanLozev Does the mentor also explain why this would happen? – Bergi Jun 02 '18 at 15:18
  • @Bergi well he doesn't. He just said that: "It's not referring back to the object that contains the function" And also he said, that: "It's the same as using arrow function". I really can't understand if this is just a mistake or his console really shows 12 and not 150. – Bogdan Lozev Jun 02 '18 at 15:24
  • @BogdanLozev If he talks specifically about `{ …, calculateValue() { … }}` as being "*the same as using an arrow function*", then yes that's just plain wrong (call it a mistake if you want). – Bergi Jun 02 '18 at 15:39
  • @Bergi, thank you for your reply you are completely right! – Bogdan Lozev Jun 02 '18 at 16:05

0 Answers0