Chrome中JS类普通方法转箭头函数报错的原因及解决方法
Hey there! Let's break down why you're hitting that Uncaught SyntaxError: Unexpected token = error and how to fix it properly.
错误原因
Your modified code uses class field syntax to assign an arrow function directly as a class method:
calculate = (weight) => (weight / 100) * _price;
Here are two key issues at play:
- Browser support limitation: This class field syntax is part of ES2022, and older versions of Chrome (released before 2019, version 74) don't natively support it. The browser interprets the
=sign in an unexpected position, hence the syntax error. - Missing
thisreference: Even if the syntax was supported, you'd run intoUncaught ReferenceError: _price is not defined. Arrow functions inheritthisfrom their surrounding constructor context, but writing_pricedirectly treats it as a global variable instead of the instance's_priceproperty.
Fixes
Option 1: Use class field syntax (modern environments)
If you're running a recent Chrome version (or using a transpiler like Babel for older setups), just fix the missing this reference:
class Product{ constructor(name, weight, price){ this._name = name; this._weight = weight; this._price = price; } calculate = (weight) => (weight / 100) * this._price; } const product = new Product("fork", 100, 1690); alert( product.calculate(200) + "won");
Modern browsers now support class fields natively, and this._price correctly references the instance's property.
Option 2: Bind a regular method (compatible with older browsers)
If you need to support older Chrome versions, stick with a regular class method and bind this in the constructor to ensure it always points to the instance:
class Product{ constructor(name, weight, price){ this._name = name; this._weight = weight; this._price = price; // Bind the method's `this` to the instance this.calculate = this.calculate.bind(this); } calculate(weight){ return (weight / 100) * this._price; } } const product = new Product("fork", 100, 1690); alert( product.calculate(200) + "won");
This approach is fully compatible with older browsers while keeping the this context consistent, just like the arrow function version.
内容的提问来源于stack exchange,提问作者Einere

