简体   繁体   English

如何将普通方法转换为Chrome中的箭头功能?

[英]how to convert normal method to arrow function in chrome?

I will make a example code for class by javascript. 我将通过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. 发生错误“未捕获的SyntaxError:Chrome中出现意外的令牌=”。

why that error occur? 为什么会发生该错误? and how to modify? 以及如何修改? thanks for watching!! 谢谢收看!

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. 如果您使用的是Babel ,则可以将其声明为一种方法,但是由于您的问题带有“ Google Chrome浏览器”标签,因此我想您需要香草ES6。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将普通函数转换为箭头函数 - Convert normal function to arrow function 我无法将此箭头 function 转换为普通 function。我已经在 chrome 的控制台面板中对此进行了测试 - am unable to convert this arrow function into Normal function. I have tested this in the console panel of the chrome 如何在普通 function 中写箭头 function - How to write arrow function in a normal function onPress 方法中箭头函数与正常函数的行为 - behavior of arrow function vs normal function in onPress method 将箭头 function 更改为正常 function? - change arrow function to normal function? 如何区分箭头函数,类和正常函数? - How can I differentiate between an arrow function, class and a normal function? 如何将箭头 function 更改为正常的 function 以使其在 Internet Explorer 中工作? - How to change arrow function to normal function that it works in Internet explorer? 如何用普通 function 替换此箭头 function? [等候接听] - How can I replace this arrow function with normal function? [on hold] JavaScript 正常 function 与箭头 function - 如何设置新的 Z31A1FD140BE4BEF2D18E5EC8DA21 - JavaScript normal function vs arrow function - how to set new scope 如何将箭头功能转换为常规功能? - How to convert arrow function into a regular function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM