[英]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.