0

I will make a example code for class by javascript. i want to implement method that return price using arrow function. below the code i wrote, and it works.

class Product{
        constructor(name, weight, price){
            this._name = name;
            this._weight = weight;
            this._price = price;
        }

        //calculate = (weight) => (weight / 100) * _price;
        calculate(weight){
            return (weight / 100) * this._price;
        }
    }

    const product = new Product("fork", 100, 1690);
    alert( product.calculate(200) + "won");

but after modify to

calculate = (weight) => (weight / 100) * _price;
/*
calculate(weight){
    return (weight / 100) * this._price;
}
*/

occur error "Uncaught SyntaxError: Unexpected token =" in chrome.

why that error occur? and how to modify? thanks for watching!!

Einere
  • 5
  • 2
  • 1
    Possible duplicate of [How to use arrow functions (public class fields) as class methods?](https://stackoverflow.com/questions/31362292/how-to-use-arrow-functions-public-class-fields-as-class-methods) – Kos Jan 22 '18 at 11:30
  • @Kos oh, i think that question is not my case... isn't? – Einere Jan 22 '18 at 11:40

1 Answers1

0

An arrow function is just a regular property rather than a method, so you can't declare it like you declare a method. Put it inside the constructor:

constructor(name, weight, price){
    this._name = name;
    this._weight = weight;
    this._price = price;

    this.calculate = weight => weight / 100 * this._price;
}

You CAN declare it like a method if you're using Babel, but since your question is tagged with "Google Chrome" I presume you want vanilla ES6.

UncleDave
  • 6,872
  • 1
  • 26
  • 44
  • ah, can't put arrow function(property) at method area? thank you very much! your code is work! i need to learn more that different method and property! – Einere Jan 22 '18 at 11:35
  • No, an arrow function on a class is just a regular property with a value that happens to be a function, so you must declare it as such. – UncleDave Jan 22 '18 at 11:36
  • thank you! i learned that arrow function is not used to method! :) – Einere Jan 21 '19 at 10:01