ES6 클래스에서 정적 상수를 선언하시겠습니까?
.class
코드에서 위치를 찾는 게 말이 되니까요
지금까지 정적 방법을 사용하여 다음 회피책을 구현했습니다.
class MyClass {
static constant1() { return 33; }
static constant2() { return 2; }
// ...
}
시제품을 만지작거릴 가능성이 있다는 것을 알지만, 많은 사람들이 이에 반대합니다.
ES6 클래스에서 상수를 구현하는 더 나은 방법이 있습니까?
다음과 같이 몇 가지 작업을 수행할 수 있습니다.
「」를 const
를 참조해 주세요.사용 사례에 따라 다음을 수행할 수 있습니다.
export const constant1 = 33;
수입하다바탕으로 「」를 도 있습니다.static
접근자 가져오기:
const constant1 = 33,
constant2 = 2;
class Example {
static get constant1() {
return constant1;
}
static get constant2() {
return constant2;
}
}
이렇게 하면 괄호가 필요하지 않습니다.
const one = Example.constant1;
아까 하신 것처럼 '아까', '아까', '아까', '아까',class
다음과 같이 비수분 특성을 추가할 수 있는 기능을 위한 구문설탕일 뿐입니다.
class Example {
}
Object.defineProperty(Example, 'constant1', {
value: 33,
writable : false,
enumerable : true,
configurable : false
});
Example.constant1; // 33
Example.constant1 = 15; // TypeError
이렇게 하면 좋을 것 같아요.
class Example {
static const constant1 = 33;
}
그러나 안타깝게도 이 클래스 속성 구문은 ES7 제안에만 있으며, 이 경우에도 추가가 허용되지 않습니다.const
부동산으로 이동합니다.
class Whatever {
static get MyConst() { return 10; }
}
let a = Whatever.MyConst;
나한테는 효과가 있는 것 같아.
하고 babel
을 사용하다
class MyClass {
static constant1 = 33;
static constant2 = {
case1: 1,
case2: 2,
};
// ...
}
MyClass.constant1 === 33
MyClass.constant2.case1 === 1
의 「 」가 해 주세요."stage-0"
.
방법:「 」
npm install --save-dev babel-preset-stage-0
// in .babelrc
{
"presets": ["stage-0"]
}
업데이트:
" " " 를 사용합니다.stage-3
이 문서에서는 다음과 같이 기술되어 있습니다.
(의도적으로) 프로토타입 데이터 속성(메서드 제외) 클래스 속성 또는 인스턴스 속성을 정의하는 직접적인 선언적 방법은 없습니다.
이것은 의도적으로 이렇게 된 것을 의미합니다.
생성자에 변수를 정의할 수 있지 않을까요?
constructor(){
this.key = value
}
사용할 수도 있습니다.Object.freeze
function) 하여 class(es6)/supervisor function(es5)을.
class MyConstants {}
MyConstants.staticValue = 3;
MyConstants.staticMethod = function() {
return 4;
}
Object.freeze(MyConstants);
// after the freeze, any attempts of altering the MyConstants class will have no result
// (either trying to alter, add or delete a property)
MyConstants.staticValue === 3; // true
MyConstants.staticValue = 55; // will have no effect
MyConstants.staticValue === 3; // true
MyConstants.otherStaticValue = "other" // will have no effect
MyConstants.otherStaticValue === undefined // true
delete MyConstants.staticMethod // false
typeof(MyConstants.staticMethod) === "function" // true
클래스를 변경하려고 하면 소프트페일이 발생합니다(오류는 발생하지 않습니다.단순히 효과가 없습니다).
그냥 모든 상수를 냉동된 물체에 넣는게 어때?
class MyClass {
constructor() {
this.constants = Object.freeze({
constant1: 33,
constant2: 2,
});
}
static get constant1() {
return this.constants.constant1;
}
doThisAndThat() {
//...
let value = this.constants.constant2;
//...
}
}
ES6 클래스의 홀수 기능을 사용하여 클래스에 정적 상수를 정의하는 방법을 만들 수 있습니다.static은 서브클래스에 의해 상속되므로 다음 작업을 수행할 수 있습니다.
const withConsts = (map, BaseClass = Object) => {
class ConstClass extends BaseClass { }
Object.keys(map).forEach(key => {
Object.defineProperty(ConstClass, key, {
value: map[key],
writable : false,
enumerable : true,
configurable : false
});
});
return ConstClass;
};
class MyClass extends withConsts({ MY_CONST: 'this is defined' }) {
foo() {
console.log(MyClass.MY_CONST);
}
}
https://stackoverflow.com/users/2784136/rodrigo-botti가 말했듯이, 제 생각엔 당신이 원하는 것은Object.freeze()
다음은 불변의 스태틱스를 가진 클래스의 예입니다.
class User {
constructor(username, age) {
if (age < User.minimumAge) {
throw new Error('You are too young to be here!');
}
this.username = username;
this.age = age;
this.state = 'active';
}
}
User.minimumAge = 16;
User.validStates = ['active', 'inactive', 'archived'];
deepFreeze(User);
function deepFreeze(value) {
if (typeof value === 'object' && value !== null) {
Object.freeze(value);
Object.getOwnPropertyNames(value).forEach(property => {
deepFreeze(value[property]);
});
}
return value;
}
나는 이 일을 했다.
class Circle
{
constuctor(radius)
{
this.radius = radius;
}
static get PI()
{
return 3.14159;
}
}
PI 값은 함수에서 반환되는 값이기 때문에 변경되지 않도록 보호됩니다.Circle을 통해 접근할 수 있습니다.PI. 할당하려는 모든 시도는 []를 통해 문자열에 할당하려는 것과 유사한 방식으로 바닥에 떨어집니다.
예를 들어 클래스를 동결함으로써 "정수"를 읽기 전용(불변)으로 만들 수 있습니다.
class Foo {
static BAR = "bat"; //public static read-only
}
Object.freeze(Foo);
/*
Uncaught TypeError: Cannot assign to read only property 'BAR' of function 'class Foo {
static BAR = "bat"; //public static read-only
}'
*/
Foo.BAR = "wut";
여기 당신이 할 수 있는 방법이 하나 더 있다.
/*
one more way of declaring constants in a class,
Note - the constants have to be declared after the class is defined
*/
class Auto{
//other methods
}
Auto.CONSTANT1 = "const1";
Auto.CONSTANT2 = "const2";
console.log(Auto.CONSTANT1)
console.log(Auto.CONSTANT2);
참고 - 순서가 중요하므로 위의 상수는 사용할 수 없습니다.
사용.
console.log(Auto.CONSTANT1);
가장 깔끔한 방법은 TypeScript를 사용하는 것입니다.클래스 상수를 구현하는 방법을 참조하십시오.
class MyClass {
static readonly CONST1: string = "one";
static readonly CONST2: string = "two";
static readonly CONST3: string = "three";
}
사용할 수 있습니다.import * as
구문을 사용합니다.클래스는 아니지만 진짜다const
변수입니다.
상수.js
export const factor = 3;
export const pi = 3.141592;
index.displaces를 표시합니다.
import * as Constants from 'Constants.js'
console.log( Constants.factor );
변수를 비공개로 선언하고 get 메서드를 사용하여 검색하기만 하면 됩니다.
class MyClass {
#myConst = 'Something';
static #anotherConst = 'Something Else';
get myConst() {
return this.#myConst; // instance method
}
static get anotherConst() {
return MyClass.#anotherConst; // static method
}
}
let myClass = new MyClass();
console.log( myClass.myConst + ' is not ' + MyClass.anotherConst );
사용자는 원래 변수를 변경할 수 없으며 개인 변수 자체 대신 get 메서드를 사용하도록 클래스를 작성할 수 있습니다.
클래스에 대해 상수/변수를 정적으로 설정하려는 경우 액세스 함수가 아닌 해시(#)를 사용하여 자리 표시자를 정의하십시오.
class Region {
// initially empty, not accessible from outside
static #empty_region = null;
/*
Make it visible to the outside and unchangeable
[note] created on first call to getter.
*/
static EMPTY() {
if (!this.#empty_region)
this.#empty_region = new Region(0, 0, 0, 0);
return this.#empty_region;
}
#reg = {x0:0, y0:0, x1:0, y1:0};
constructor(x0, y0, x1, y1) {
this.setRegion(x0, y0, x1, y1);
}
// setters/getters
}
구현:
let someRegion = Region.EMPTY();
let anotherRegion = Region.EMPTY();
함수 구문과 클래스 구문을 혼합하고 일치시키는 것이 쉬운 경우 클래스 뒤에 상수를 선언할 수 있습니다('리프트'된 상수는 표시됨). Visual Studio 코드는 혼합 구문을 자동 포맷하는 데 어려움을 겪습니다(작동 가능하지만).
class MyClass {
// ...
}
MyClass.prototype.consts = {
constant1: 33,
constant2: 32
};
mc = new MyClass();
console.log(mc.consts.constant2);
다른 응답에 더하여 다른 클래스에서 사용할 클래스를 내보내야 합니다.이것은 그것의 타이프스크립트 버전입니다.
//Constants.tsx
const DEBUG: boolean = true;
export class Constants {
static get DEBUG(): boolean {
return DEBUG;
}
}
//Anotherclass.tsx
import { Constants } from "Constants";
if (Constants.DEBUG) {
console.log("debug mode")
}
여기예요.
const Status = Object.freeze(class Status {
static Disabled = 0
static Live = 1
})
언급URL : https://stackoverflow.com/questions/32647215/declaring-static-constants-in-es6-classes
'it-source' 카테고리의 다른 글
한 열에 따라 중복 항목에서 첫 번째 행 가져오기 마리아DB (0) | 2022.11.20 |
---|---|
목록을 되돌리거나 거꾸로 루프하려면 어떻게 해야 하나요? (0) | 2022.11.20 |
오류 갤러 클러스터: wsrep_sst_rsync --role 'joiner'에서 'ready'를 읽지 못했습니다. (0) | 2022.11.20 |
Python을 사용하여 cURL 명령을 실행하는 방법은 무엇입니까? (0) | 2022.11.20 |
Swing GUI를 가장 잘 포지셔닝하는 방법 (0) | 2022.11.20 |