Bagaimanakah anda mengurus pembolehubah kelas dalam kelas ES6 apabila ia tidak disokong secara asli?

Barbara Streisand
Lepaskan: 2024-11-15 12:46:02
asal
486 orang telah melayarinya

How do you manage class variables in ES6 classes when they are not natively supported?

Class Variable Alternatives in ES6

In ES5, developers often used a comfortable pattern to create classes and class variables, as demonstrated in the following code:

// ES 5
FrameWork.Class({

    variable: 'string',
    variable2: true,

    init: function(){

    },

    addItem: function(){

    }

});
Salin selepas log masuk

However, in ES6, creating classes natively doesn't include the option to have class variables, as shown below:

// ES6
class MyClass {
    const MY_CONST = 'string'; // <-- this is not possible in ES6
    constructor(){
        this.MY_CONST;
    }
}
Salin selepas log masuk

This is because ES6 classes are restricted to containing methods. While it's possible to set this.myVar in the constructor, it's undesirable to clutter the constructor, especially with large classes.

Several approaches have been considered to address this issue, including:

  • Creating a ClassConfig handler: Pass a parameter object to the handler, which is declared separately from the class. The handler would then attach to the class. WeakMaps could potentially be integrated for this purpose.
  • A stage 3 proposal: This proposal allows declaring variables within a class declaration/expression body using the syntax varName = value. It's expected to become obsolete in the future.
  • Setting constructor variables: While not a perfect solution, constructor(){ this.foo = bar } can be used to set instance variables.
  • ES7 property initializers: A new proposal for ES7 allows declaring more concise instance variables using class declarations and expressions.

Atas ialah kandungan terperinci Bagaimanakah anda mengurus pembolehubah kelas dalam kelas ES6 apabila ia tidak disokong secara asli?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan