Programing

ECMAScript 6 클래스의 게터와 세터는 무엇입니까?

lottogame 2020. 8. 25. 19:17
반응형

ECMAScript 6 클래스의 게터와 세터는 무엇입니까?


ECMAScript 6 클래스에서 getter와 setter의 요점이 무엇인지 혼란 스럽습니다. 목적은 무엇입니까? 아래는 제가 언급하는 예입니다.

class Employee {

    constructor(name) {
        this._name = name;
    }

    doWork() {
        return `${this._name} is working`;
    }

    get name() {
        return this._name.toUpperCase();
    }

    set name(newName){
        if(newName){ 
            this._name = newName;
        }
    }
}

이러한 setter 및 getter를 사용하면 괄호를 사용하지 않고 속성을 직접 사용할 수 있습니다.

var emp = new Employee("TruMan1");

if (emp.name) { 
  // uses the get method in the background
}

emp.name = "New name"; // uses the setter in the background

이것은 속성의 값을 설정하고 얻는 것입니다.


ES6의 getter 및 setter는 ES5를 포함하여 다른 언어에서 수행하는 것과 동일한 용도로 사용됩니다. ES5 Object.defineProperty는 덜 깨끗하고 사용하기 더 번거롭지 만 이미을 통해 getter 및 setter를 허용 합니다.

효과적으로 getter 및 setter를 사용하면 읽기 및 쓰기에 표준 속성 액세스 표기법을 사용할 수 있으며 명시적인 getter 및 setter 메서드 없이도 속성을 검색하고 변경하는 방법을 사용자 지정할 수 있습니다.

위의 Employee 클래스에서 name이것은 다음과 같이 속성에 액세스 할 수 있음을 의미합니다 .

console.log(someEmployee.name);

그것은 것 보면 일반적인 속성 액세스처럼,하지만 실제로 부를 것이다 toUpperCase그것을 반환하기 전에 이름을. 마찬가지로 다음을 수행합니다.

someEmployee.name = null;

setter에 액세스하고의 setter에 _name도입 된 guard 절 때문에 내부 속성을 수정하지 않습니다 name.

일반적인 질문 인 왜 게터와 세터를 사용합니까?를 참조하십시오 . 회원 액세스 기능을 수정할 수있는 것이 유용한 이유에 대한 자세한 내용은


ES6 getter 및 setter는 Java의 유사한 개념과 실질적으로 다른 동기를 갖습니다.

Java에서 getter 및 setter는 클래스가 JavaBean을 정의 할 수 있도록합니다. getter와 setter의 요점은 bean이 public 필드에서 암시하는 것과 완전히 직교하는 "인터페이스"를 가질 수 있다는 것입니다. 그래서 JavaBean 속성이 아닌 "name"필드를 가질 수 있고 필드가 아닌 JavaBean 속성 "address"를 가질 수 있습니다.

JavaBean 속성은 Java 리플렉션을 통해 수천 개의 프레임 워크 (예 : Hibernate)에서 "검색 가능"합니다. 따라서 getter 및 setter는 빈 속성을 "노출"하는 표준 방법의 일부입니다.

Getters and setters, being functions, also have the value that they "abstract" the implementation. It can be EITHER a field or a computed ("synthetic") value. So if I have a bean property called "zipcode", that starts out as stored string. Now suppose I want to change it to be a value computed from address/city/state?

If I use a field, this code breaks:

      String zipcode = address.zipcode();

But if I use a getter, this does not break:

      String zipcode = address.getZipcode();

JavaScript doesn't have anything like JavaBeans. So far as I've read, the intended value of GET and SET is limited to the aforementions "synthetic" (computed) properties.

But it's somewhat better than java in that while Java doesn't allow you to compatibly convert a "field" to a method, ES6 GET and SET allows that.

That is, if I have:

       var zipcode = address.zipcode;

If I change zipcode from being a standard object property to a getter, the above code now calls the GET function.

Note that if I didn't include GET in the definition, this would NOT invoke the zipcode GET method. Instead, it would merely assign the function zipcode to the var.

So I think these are some important distinctions to understand betweeen Java and JavaScript ES6 getters and setters.

참고URL : https://stackoverflow.com/questions/28222276/what-are-getters-and-setters-for-in-ecmascript-6-classes

반응형