簡體   English   中英

如何將普通方法轉換為Chrome中的箭頭功能?

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

我將通過javascript制作一個示例代碼。 我想實現使用箭頭函數返回價格的方法。 下面我寫的代碼,它的工作原理。

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");

但修改為

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

發生錯誤“未捕獲的SyntaxError:Chrome中出現意外的令牌=”。

為什么會發生該錯誤? 以及如何修改? 謝謝收看!

箭頭函數只是常規屬性,而不是方法,因此不能像聲明方法那樣聲明它。 將其放入構造函數中:

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

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

如果您使用的是Babel ,則可以將其聲明為一種方法,但是由於您的問題帶有“ Google Chrome瀏覽器”標簽,因此我想您需要香草ES6。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM