You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. 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.
  2. Missing this reference: Even if the syntax was supported, you'd run into Uncaught ReferenceError: _price is not defined. Arrow functions inherit this from their surrounding constructor context, but writing _price directly treats it as a global variable instead of the instance's _price property.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:57:16