SlideShare una empresa de Scribd logo
1 de 21
{ for AngularJS, React}
고급 자바스크립트
4. getter, setter ofclass
탑크리에듀
IT기술 칼럼
와 함께하는
{ ES6 }4. getter, setter of class
자바스크립트의 프로퍼티는 성질에 따라서 데이터 프로퍼티와 접근자 프로퍼티로
구분합니다. 이번 시간에는 접근자 프로퍼티와 관련된 얘기입니다.
이해를 돕기 위해서 예를 들어 보면, 자바언어에서 getter, setter 메소드는 로직을
위한 메소드가 아니라 객체가 갖고 있는 변수에 접근해서 값을 가져가거나 수정하
는 용도로 사용하는 메소드입니다.
부가적으로 값을 가공하는 로직정도를 두기도 합니다.
자바스크립트는 자바언어에서 지원하는 접근자(예: private, protected, public) 개념
이 없기 때문에 자바스크립트의 게터, 세터를 단지 프로퍼티의 값을 접근하거나 수
정하는 용도로 사용한다면 사실 큰 의미가 없습니다.
프로퍼티에 직접 접근해서 사용할 수 있기 때문이지요. 차라리, 자바스크립트의 게
터, 세터는 값을 조작해서 가져가거나 조작해서 수정하고자 하는 부가적인 로직을
두고 싶은 경우에 사용한다고 이해하시는게 좋겠습니다.
{ ES6 }4. getter, setter of class
class4.es6
classCar{
constructor(name){
this.name= name;
}
get_name(){
returnthis.name;
}
set_name(name){
this.name= name;
}
}
varcar= newCar('A');
console.log(car);
//{ name:'A'}
자바스크립트는 클래스문법에서 get, set 키워드로 정의하는 함수 선언방법을 도입했습니다.
우선, 클래스 문법의 사용예제를 살펴보겠습니다.
{ ES6 }4. getter, setter of class
console.log(Object.getOwnPropertyNames(Car.prototype));
//['constructor','_name']
console.log(Object.getOwnPropertyDescriptor(Car.prototype,'_name'));
/*
{ get:[Function:get_name],
set:[Function:set_name],
enumerable:false,
configurable:true}
*/
console.log(car._name);//getter
//A
car._name= 'B';// 할당연산자와같이사용하면setter
console.log(car._name);
//B
선언방법은 함수 앞에 get, set 키워드를 설정하는 것 입니다.
get, set키워드가 붙은 함수명은 일반적으로 같은 이름을 사용합니다. 이렇게 선언된 게터, 세
터 메소드를 통해 객체가 갖고 있는 변수에 접근하는 것을 제어합니다. 다른 랭귀지에서의 게
터, 세터 메소드와 사용 용도는 같지만 이용하는 방법은 차이가 있습니다.
{ ES6 }4. getter, setter of class
console.log(car._name);//getter
//A
car._name= 'B';// 할당연산자와같이사용하면setter
console.log(car._name);
//B
자바스크립트의 게터, 세터 메소드는 괄호없이 사용해야 합니다. 할당연산자가 없으면 게터로
작동하고 할당연산자와 같이 사용하면 세터로 작동합니다.
console.log(Object.getOwnPropertyNames(Car.prototype));
//[ 'constructor','_name']
자바스크립트의 게터, 세터 메소드는 생성자 함수의 프로토타입 객체에 추가되며 get, set 두
개의 함수는 결국 하나의 프로퍼티의 서술자 객체의 속성으로 반영되어 처리됩니다.
{ ES6 }4. getter, setter of class
console.log(Object.getOwnPropertyDescriptor(Car.prototype,'_name'));
/*
{ get:[Function:get_name],
set:[Function:set_name],
enumerable:false,
configurable:true}
*/
자바스크립트의 get, set 설정으로 추가된 프로퍼티는 접근자 프로퍼티입니다.
get: 값을조회하는함수다.기본값은undefined이다.
set:값을수정하는함수다.기본값은undefined이다.
enumerable:for-in루프나Object.keys()메소드를사용하여열거할수있다.
configurable:프로퍼티속성을변경,삭제할수있다.
접근자 프로퍼티의 속성을 정의하는 서술자 객체의 프로퍼티의 용도는 다음과 같습니다.
{ ES6 }4. getter, setter of class
이해를 돕기 위해서, 똑같은 결과를 얻을 수 있는 코드를 ES5 함수문법으로 작성해서 살펴보
겠습니다.
functionCar(name){
this.name=name;
}
Object.defineProperty(Car.prototype,'_name',{
get:function(){
returnthis.name;
},
set:function(name){
this.name= name;
},
enumerable:false,
configurable:true
});
varcar= newCar('A');
console.log(car);
//{ name:'A' }
console.log(Object.getOwnPropertyNames(Car.prototype));
//[ 'constructor','_name']
example4.js
{ ES6 }4. getter, setter of class
console.log(Object.getOwnPropertyDescriptor(Car.prototype,'_name'));
/*
{ get:[Function:get_name],
set:[Function:set_name],
enumerable:false,
configurable:true}
*/
console.log(car._name);//getter
//A
car._name= 'B';//할당연산자와같이사용하면setter
console.log(car._name);
//B
그런데, 객체의 변수 name에 직접 접근할 수 있는 데, 접근자 프로퍼티를 설정하여
get, set 함수를 둘 필요가 있을까요?
get, set 함수에 부가적인 처리로직을 둔다면 의미가 생깁니다.
반대로 값을 가져가거나 수정할 때 처리하는 부가적인 로직이 없다면 접근자 프로퍼티를 둘
필요가 없습니다.
{ ES6 }4. getter, setter of class
example4-2.js
functionCar(name){
//this.name= name;// 아래코드로대체한다.
Object.defineProperty(this,'name',{
value:name,
writable:false,
enumerable:true,
configurable:true
});
}
프로퍼티 서술자 객체를 사용하여 새로 만들어지는 객체에 프로퍼티 ‘name’을 추가합니다.
이 때, 프로퍼티 속성 중 writable 값을 false로 선언합니다.
이러면 이 프로퍼티의 값은 변경할 수 없게 됩니다. 그래서, 다음과 같은 현상이 벌어집니다.
“car._name=’B’” 처럼 세터를 사용하여도 “car.name=’B’” 처럼 직접 프로퍼티를 수정하려고
시도하여도 변경되지 않으며 예외도 발생하지 않습니다.
값이 변경되지 않는데 예외가 발생하지 않는군요!
{ ES6 }4. getter, setter of class
console.log(car._name);
//A
car._name= 'B';
console.log(car._name);
//A
세터를 사용하는 경우 다음처럼 예외를 던져 친절하게 수정할 수 없다고 알려 줄 수 있습니다.
Object.defineProperty(Car.prototype,'_name',{
get:function(){
returnthis.name;
},
//set:function(name){ //아래코드로대체한다.
// this.name=name;
//},
set:function(name){
thrownewError('값을변경할수없습니다.');
},
enumerable:false,
configurable:true
});
{ ES6 }4. getter, setter of class
그러나, 사용자가 세터를 통해서 값에 접근하지 않고 직접 값을 갖고 있는 프로퍼티에 접근할
수 있기 때문에 완전한 해결책은 아닙니다. 따라서, 데이터 프로퍼티 접근 시 무언가 로직을
수행하여 사용자에게 알려줄 수 있는 방법이 필요하다는 결론에 다다르게 됩니다.
이 때, 프록시 객체의 필요성이 대두됩니다. 아래 example4-3.js에서 사용방법을 살펴보겠습니
다.
다음은 테스트를 위해 변경한 전체 소스코드입니다.
example4-2.js
functionCar(name){
//this.name= name;
Object.defineProperty(this,'name',{
value:name,
writable:false,
enumerable:true,
configurable:true
});
}
{ ES6 }4. getter, setter of class
Object.defineProperty(Car.prototype,'_name',{
get:function(){
returnthis.name;
},
//set:function(name){
// this.name=name;
//},
set:function(name){
thrownewError('값을변경할수없습니다.');
},
enumerable:false,
configurable:true
});
varcar= newCar('A');
console.log(car);
//{ name:'A'}
console.log(Object.getOwnPropertyNames(Car.prototype));
//[ 'constructor','_name']
console.log(Object.getOwnPropertyDescriptor(Car.prototype,'_name'));
{ ES6 }4. getter, setter of class
/*
{ get:[Function:get_name],
set:[Function:set_name],
enumerable:false,
configurable:true}
*/
console.log(car._name);//getter
//A
try{
car._name= 'B';//할당연산자와같이사용하면setter
} catch(e) {
console.log('catch>>'+ e.name);
console.log('catch>>'+ e.message);
}
console.log(car._name);
//A
{ ES6 }4. getter, setter of class
다음은 데이터 프로퍼티 name의 서술자 속성 중, “writable: false” 설정으로 값을 변경할 수 없
으므로 이를 사용자에게 알려주기위한 설정방법입니다.
example4-3.js
functionCar(name,color){
Object.defineProperty(this,'name',{
value:name,
writable:false,
enumerable:true,
configurable:true
});
this.color=color;
}
varcar= newCar('A','White');
console.log(car);
//{ name:'A',color:'White'}
console.log(car.name);
//A
car.name='B';
//writable:false설정으로변경되지않지만,예외도발생하지않는다.
console.log(car.name);
//A
{ ES6 }4. getter, setter of class
varhandler= {
set:function(target,property,value,receiver){
if(property=== 'name'){
thrownewError('name프로퍼티는변경할수 없습니다.')
}
//처리되어야하는원래로직을수행한다.
target[property]= value;
}
};
varproxyCar= newProxy(car,handler);
//사용자에게car 객체대신proxyCar객체를주면
//사용자가프로퍼티를변경하고자하는경우
//set트랩이기동한다.
try{
proxyCar.name='B';
} catch(e) {
console.log(e.message);
//name프로퍼티는변경할수없습니다.
}
proxyCar.color='Red';
console.log(car);
//{ name:'A',color:'Red'}
{ ES6 }4. getter, setter of class
원래 값을 갖고 있는 car 객체가 target입니다. 이를 프록시 객체로 감싼 객체를 변수 proxyCar
가 가리킵니다.
타겟 객체에 접근하기 전 프록시객체 생성 시 설정한 handler 객체의 트랩함수가 기동합니다.
이 때, “writable: false”로 설정된 name 프로퍼티를 수정하고 하는 경우 예외를 발생시켜 사용
자에게 알려주는 방식입니다.
이번 시간의 주제로 돌아옵니다. 자바스크립트의 객체 프로퍼티는 두 가지 용도로 사용될 수
있다는 것을 기억하시면 좋겠습니다.
1. 데이터 프로퍼티 : 변수, 함수를 보관한다.
2. 접근자 프로퍼티 : 변수, 함수의 접근 시 부가적인 작업을 수행한 후 데이터 프로퍼티와 연계한다.
객체 프로퍼티의 두 가지 용도
{ ES6 }4. getter, setter of class
게터, 세터의 필요성 및 서술자 속성의 역할이 무엇인지 파악할 수 있는 예제를 살펴보면서 마
치도록 하겠습니다.
example-configurable.js
varperson={};
Object.defineProperty(person,'name',{
value:'B',
writable:true,
enumerable:true,
configurable:false
});
console.log(Object.getOwnPropertyDescriptor(person,'name'));
//{ value:'B',
// writable:true,
// enumerable:true,
// configurable:true}
{ ES6 }4. getter, setter of class
console.log(person);
//{ name:'B'}
person.name= 'A';
console.log(person);
//{ name:'A'}
deleteperson.name;//configurable:false설정으로삭제되지않는다.
console.log(Object.getOwnPropertyDescriptor(person,'name'));
//{ value:'A',
// writable:true,
// enumerable:true,
// configurable:false}
“delete person.name;” 코드는 name 프로퍼티의 서술자 설정 중, “configurable: false” 설정으
로 삭제되지 않습니다.
{ ES6 }4. getter, setter of class
example-needs-get-set.js
varperson={};
person.firstName='Tom';
person.lastName= 'Cruise';
console.log(person);
//{ firstName:'Tom',lastName:'Cruise'}
Object.defineProperty(person,'fullName',{
get:function(){
returnthis.firstName+ '' +this.lastName;
},
set:function(fullName){
varnames= fullName.split('');
this.firstName=names[0];
this.lastName= names[1];
},
enumerable:false,
configurable:true
});
{ ES6 }4. getter, setter of class
//enumerable:false설정으로fullName접근자프로퍼티는보이지않는다.
console.log(person);
//{ firstName:'Tom',lastName:'Cruise'}
console.log(person.fullName);// 게터
//Tom Cruise
person.fullName='BradPitt';// 세터
console.log(person.fullName);
//BradPitt
person 객체의 fullName 프로퍼티의 서술자 설정 중, “enumerable: false”로 설정했으므로
“console.log(person);” 코드로는 fullName 프로퍼티가 포함되지 않습니다.
{ ES6 }4. getter, setter of class
송석원
현재 :
- 탑크리에듀교육센터 자바, 스프링 프레임워크, JPA, Querydsl,
AngularJS, React, Android 분야 전임강사
경력 :
- 오라클자바커뮤니티교육센터
자바, 스프링, JPA, Node.JS, AngularJS, React, Android 전임강사
- 탑크리에듀 교육센터
Java, Spring Data JPA, Querydsl, SQL 교재 편찬위원
- 회원수 14,000명의 오라클자바커뮤니티 운영 및 관리
- SK T-아카데미 스프링 프레임워크 강의
- 정철 어학원
탑크리에듀교육센터 Tel. 02-851-4790 http://www.topcredu.co.kr
Copyrights ⓒ Topcredu. All rights Reserved.

Más contenido relacionado

La actualidad más candente

0.javascript기본(~3일차내)
0.javascript기본(~3일차내)0.javascript기본(~3일차내)
0.javascript기본(~3일차내)Sung-hoon Ma
 
자바스크립트 기초문법~함수기초
자바스크립트 기초문법~함수기초자바스크립트 기초문법~함수기초
자바스크립트 기초문법~함수기초진수 정
 
Scala type class pattern
Scala type class patternScala type class pattern
Scala type class patternYong Joon Moon
 
Angular2 가기전 Type script소개
 Angular2 가기전 Type script소개 Angular2 가기전 Type script소개
Angular2 가기전 Type script소개Dong Jun Kwon
 
Java 8 api :: lambda 이용하기
Java 8 api :: lambda 이용하기Java 8 api :: lambda 이용하기
Java 8 api :: lambda 이용하기rupert kim
 
Lambda 란 무엇인가
Lambda 란 무엇인가Lambda 란 무엇인가
Lambda 란 무엇인가Vong Sik Kong
 
Start IoT with JavaScript - 1.기초
Start IoT with JavaScript - 1.기초Start IoT with JavaScript - 1.기초
Start IoT with JavaScript - 1.기초Park Jonggun
 
Multithread programming 20151206_서진택
Multithread programming 20151206_서진택Multithread programming 20151206_서진택
Multithread programming 20151206_서진택JinTaek Seo
 
Effective c++ Chapter1,2
Effective c++ Chapter1,2Effective c++ Chapter1,2
Effective c++ Chapter1,2문익 장
 
파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기Yong Joon Moon
 
파이썬 class 및 function namespace 이해하기
파이썬 class 및 function namespace 이해하기파이썬 class 및 function namespace 이해하기
파이썬 class 및 function namespace 이해하기Yong Joon Moon
 
파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기 파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기 Yong Joon Moon
 
파이썬 반복자 생성자 이해하기
파이썬 반복자 생성자 이해하기파이썬 반복자 생성자 이해하기
파이썬 반복자 생성자 이해하기Yong Joon Moon
 
파이썬 iterator generator 이해하기
파이썬 iterator generator 이해하기파이썬 iterator generator 이해하기
파이썬 iterator generator 이해하기Yong Joon Moon
 
파이썬 Special method 이해하기
파이썬 Special method 이해하기파이썬 Special method 이해하기
파이썬 Special method 이해하기Yong Joon Moon
 
파이썬 sqlite 이해하기
파이썬 sqlite 이해하기파이썬 sqlite 이해하기
파이썬 sqlite 이해하기Yong Joon Moon
 
자바스크립트 함수
자바스크립트 함수자바스크립트 함수
자바스크립트 함수유진 변
 
Secrets of the JavaScript Ninja - Chapter 3. Functions are Fundamental
Secrets of the JavaScript Ninja - Chapter 3. Functions are FundamentalSecrets of the JavaScript Ninja - Chapter 3. Functions are Fundamental
Secrets of the JavaScript Ninja - Chapter 3. Functions are FundamentalHyuncheol Jeon
 

La actualidad más candente (20)

0.javascript기본(~3일차내)
0.javascript기본(~3일차내)0.javascript기본(~3일차내)
0.javascript기본(~3일차내)
 
자바스크립트 기초문법~함수기초
자바스크립트 기초문법~함수기초자바스크립트 기초문법~함수기초
자바스크립트 기초문법~함수기초
 
Scala type class pattern
Scala type class patternScala type class pattern
Scala type class pattern
 
Angular2 가기전 Type script소개
 Angular2 가기전 Type script소개 Angular2 가기전 Type script소개
Angular2 가기전 Type script소개
 
Javascript
JavascriptJavascript
Javascript
 
Java 8 api :: lambda 이용하기
Java 8 api :: lambda 이용하기Java 8 api :: lambda 이용하기
Java 8 api :: lambda 이용하기
 
Lambda 란 무엇인가
Lambda 란 무엇인가Lambda 란 무엇인가
Lambda 란 무엇인가
 
Start IoT with JavaScript - 1.기초
Start IoT with JavaScript - 1.기초Start IoT with JavaScript - 1.기초
Start IoT with JavaScript - 1.기초
 
Multithread programming 20151206_서진택
Multithread programming 20151206_서진택Multithread programming 20151206_서진택
Multithread programming 20151206_서진택
 
Effective c++ Chapter1,2
Effective c++ Chapter1,2Effective c++ Chapter1,2
Effective c++ Chapter1,2
 
파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기
 
파이썬 class 및 function namespace 이해하기
파이썬 class 및 function namespace 이해하기파이썬 class 및 function namespace 이해하기
파이썬 class 및 function namespace 이해하기
 
파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기 파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기
 
파이썬 반복자 생성자 이해하기
파이썬 반복자 생성자 이해하기파이썬 반복자 생성자 이해하기
파이썬 반복자 생성자 이해하기
 
Redux
ReduxRedux
Redux
 
파이썬 iterator generator 이해하기
파이썬 iterator generator 이해하기파이썬 iterator generator 이해하기
파이썬 iterator generator 이해하기
 
파이썬 Special method 이해하기
파이썬 Special method 이해하기파이썬 Special method 이해하기
파이썬 Special method 이해하기
 
파이썬 sqlite 이해하기
파이썬 sqlite 이해하기파이썬 sqlite 이해하기
파이썬 sqlite 이해하기
 
자바스크립트 함수
자바스크립트 함수자바스크립트 함수
자바스크립트 함수
 
Secrets of the JavaScript Ninja - Chapter 3. Functions are Fundamental
Secrets of the JavaScript Ninja - Chapter 3. Functions are FundamentalSecrets of the JavaScript Ninja - Chapter 3. Functions are Fundamental
Secrets of the JavaScript Ninja - Chapter 3. Functions are Fundamental
 

Similar a (AngularJS,React를 위한 자바스크립트)getter, setter of class_AngularJS교육/ReactJS교육/자바스크립트교육추천

(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...
(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...
(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍Young-Beom Rhee
 
Javascript - Function
Javascript - FunctionJavascript - Function
Javascript - Functionwonmin lee
 
GraphQL overview #2
GraphQL overview #2GraphQL overview #2
GraphQL overview #2기동 이
 
Es2015 Simple Overview
Es2015 Simple OverviewEs2015 Simple Overview
Es2015 Simple OverviewKim Hunmin
 
프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oopYoung-Beom Rhee
 
Start IoT with JavaScript - 6.함수
Start IoT with JavaScript - 6.함수Start IoT with JavaScript - 6.함수
Start IoT with JavaScript - 6.함수Park Jonggun
 
Angular2 router&http
Angular2 router&httpAngular2 router&http
Angular2 router&httpDong Jun Kwon
 
Role Of Server In Ajax Korean
Role Of Server In Ajax KoreanRole Of Server In Ajax Korean
Role Of Server In Ajax KoreanTerry Cho
 
JavaScript Patterns - Chapter 3. Literals and Constructors
JavaScript Patterns - Chapter 3. Literals and ConstructorsJavaScript Patterns - Chapter 3. Literals and Constructors
JavaScript Patterns - Chapter 3. Literals and ConstructorsHyuncheol Jeon
 
Refactoring - Chapter 8.2
Refactoring - Chapter 8.2Refactoring - Chapter 8.2
Refactoring - Chapter 8.2Ji Ung Lee
 
[오픈소스컨설팅]MyBatis Basic
[오픈소스컨설팅]MyBatis Basic[오픈소스컨설팅]MyBatis Basic
[오픈소스컨설팅]MyBatis BasicJi-Woong Choi
 
GraphQL overview
GraphQL overviewGraphQL overview
GraphQL overview기동 이
 
[ES6] 4. Spread, Rest parameter
[ES6] 4. Spread, Rest parameter[ES6] 4. Spread, Rest parameter
[ES6] 4. Spread, Rest parameterHan JaeYeab
 
ECMA Script 5 & 6
ECMA Script 5 & 6ECMA Script 5 & 6
ECMA Script 5 & 6sewoo lee
 
파이썬 모듈 패키지
파이썬 모듈 패키지파이썬 모듈 패키지
파이썬 모듈 패키지SeongHyun Ahn
 
Startup JavaScript 6 - 함수, 스코프, 클로저
Startup JavaScript 6 - 함수, 스코프, 클로저Startup JavaScript 6 - 함수, 스코프, 클로저
Startup JavaScript 6 - 함수, 스코프, 클로저Circulus
 

Similar a (AngularJS,React를 위한 자바스크립트)getter, setter of class_AngularJS교육/ReactJS교육/자바스크립트교육추천 (20)

(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...
(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...
(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...
 
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
 
Javascript - Function
Javascript - FunctionJavascript - Function
Javascript - Function
 
GraphQL overview #2
GraphQL overview #2GraphQL overview #2
GraphQL overview #2
 
Es2015 Simple Overview
Es2015 Simple OverviewEs2015 Simple Overview
Es2015 Simple Overview
 
프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop
 
Start IoT with JavaScript - 6.함수
Start IoT with JavaScript - 6.함수Start IoT with JavaScript - 6.함수
Start IoT with JavaScript - 6.함수
 
Angular2 router&http
Angular2 router&httpAngular2 router&http
Angular2 router&http
 
Role Of Server In Ajax Korean
Role Of Server In Ajax KoreanRole Of Server In Ajax Korean
Role Of Server In Ajax Korean
 
Nodejs express
Nodejs expressNodejs express
Nodejs express
 
Xe hack
Xe hackXe hack
Xe hack
 
Java(3/4)
Java(3/4)Java(3/4)
Java(3/4)
 
JavaScript Patterns - Chapter 3. Literals and Constructors
JavaScript Patterns - Chapter 3. Literals and ConstructorsJavaScript Patterns - Chapter 3. Literals and Constructors
JavaScript Patterns - Chapter 3. Literals and Constructors
 
Refactoring - Chapter 8.2
Refactoring - Chapter 8.2Refactoring - Chapter 8.2
Refactoring - Chapter 8.2
 
[오픈소스컨설팅]MyBatis Basic
[오픈소스컨설팅]MyBatis Basic[오픈소스컨설팅]MyBatis Basic
[오픈소스컨설팅]MyBatis Basic
 
GraphQL overview
GraphQL overviewGraphQL overview
GraphQL overview
 
[ES6] 4. Spread, Rest parameter
[ES6] 4. Spread, Rest parameter[ES6] 4. Spread, Rest parameter
[ES6] 4. Spread, Rest parameter
 
ECMA Script 5 & 6
ECMA Script 5 & 6ECMA Script 5 & 6
ECMA Script 5 & 6
 
파이썬 모듈 패키지
파이썬 모듈 패키지파이썬 모듈 패키지
파이썬 모듈 패키지
 
Startup JavaScript 6 - 함수, 스코프, 클로저
Startup JavaScript 6 - 함수, 스코프, 클로저Startup JavaScript 6 - 함수, 스코프, 클로저
Startup JavaScript 6 - 함수, 스코프, 클로저
 

Más de 탑크리에듀(구로디지털단지역3번출구 2분거리)

[뷰제이에스학원]뷰제이에스(Vue.js) 프로그래밍 입문(프로그레시브 자바스크립트 프레임워크)
[뷰제이에스학원]뷰제이에스(Vue.js) 프로그래밍 입문(프로그레시브 자바스크립트 프레임워크)[뷰제이에스학원]뷰제이에스(Vue.js) 프로그래밍 입문(프로그레시브 자바스크립트 프레임워크)
[뷰제이에스학원]뷰제이에스(Vue.js) 프로그래밍 입문(프로그레시브 자바스크립트 프레임워크)탑크리에듀(구로디지털단지역3번출구 2분거리)
 
(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...
(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...
(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
[자마린교육/자마린실습]자바,스프링프레임워크(스프링부트) RESTful 웹서비스 구현 실습,자마린에서 스프링 웹서비스를 호출하고 응답 JS...
[자마린교육/자마린실습]자바,스프링프레임워크(스프링부트) RESTful 웹서비스 구현 실습,자마린에서 스프링 웹서비스를 호출하고 응답 JS...[자마린교육/자마린실습]자바,스프링프레임워크(스프링부트) RESTful 웹서비스 구현 실습,자마린에서 스프링 웹서비스를 호출하고 응답 JS...
[자마린교육/자마린실습]자바,스프링프레임워크(스프링부트) RESTful 웹서비스 구현 실습,자마린에서 스프링 웹서비스를 호출하고 응답 JS...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
C#기초에서 윈도우, 스마트폰 앱개발 과정(c#.net, ado.net, win form, wpf, 자마린)_자마린학원_씨샵교육_WPF학원...
C#기초에서 윈도우, 스마트폰 앱개발 과정(c#.net, ado.net, win form, wpf, 자마린)_자마린학원_씨샵교육_WPF학원...C#기초에서 윈도우, 스마트폰 앱개발 과정(c#.net, ado.net, win form, wpf, 자마린)_자마린학원_씨샵교육_WPF학원...
C#기초에서 윈도우, 스마트폰 앱개발 과정(c#.net, ado.net, win form, wpf, 자마린)_자마린학원_씨샵교육_WPF학원...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
자바, 웹 기초와 스프링 프레임워크 & 마이바티스 재직자 향상과정(자바학원/자바교육/자바기업출강]
자바, 웹 기초와 스프링 프레임워크 & 마이바티스 재직자 향상과정(자바학원/자바교육/자바기업출강]자바, 웹 기초와 스프링 프레임워크 & 마이바티스 재직자 향상과정(자바학원/자바교육/자바기업출강]
자바, 웹 기초와 스프링 프레임워크 & 마이바티스 재직자 향상과정(자바학원/자바교육/자바기업출강]탑크리에듀(구로디지털단지역3번출구 2분거리)
 
3. 안드로이드 애플리케이션 구성요소 3.2인텐트 part01(안드로이드학원/안드로이드교육/안드로이드강좌/안드로이드기업출강]
3. 안드로이드 애플리케이션 구성요소 3.2인텐트 part01(안드로이드학원/안드로이드교육/안드로이드강좌/안드로이드기업출강]3. 안드로이드 애플리케이션 구성요소 3.2인텐트 part01(안드로이드학원/안드로이드교육/안드로이드강좌/안드로이드기업출강]
3. 안드로이드 애플리케이션 구성요소 3.2인텐트 part01(안드로이드학원/안드로이드교육/안드로이드강좌/안드로이드기업출강]탑크리에듀(구로디지털단지역3번출구 2분거리)
 

Más de 탑크리에듀(구로디지털단지역3번출구 2분거리) (20)

자마린.안드로이드 기본 내장레이아웃(Built-In List Item Layouts)
자마린.안드로이드 기본 내장레이아웃(Built-In List Item Layouts)자마린.안드로이드 기본 내장레이아웃(Built-In List Item Layouts)
자마린.안드로이드 기본 내장레이아웃(Built-In List Item Layouts)
 
(스프링프레임워크 강좌)스프링부트개요 및 HelloWorld 따라하기
(스프링프레임워크 강좌)스프링부트개요 및 HelloWorld 따라하기(스프링프레임워크 강좌)스프링부트개요 및 HelloWorld 따라하기
(스프링프레임워크 강좌)스프링부트개요 및 HelloWorld 따라하기
 
자마린 iOS 멀티화면 컨트롤러_네비게이션 컨트롤러, 루트 뷰 컨트롤러
자마린 iOS 멀티화면 컨트롤러_네비게이션 컨트롤러, 루트 뷰 컨트롤러자마린 iOS 멀티화면 컨트롤러_네비게이션 컨트롤러, 루트 뷰 컨트롤러
자마린 iOS 멀티화면 컨트롤러_네비게이션 컨트롤러, 루트 뷰 컨트롤러
 
[IT교육/IT학원]Develope를 위한 IT실무교육
[IT교육/IT학원]Develope를 위한 IT실무교육[IT교육/IT학원]Develope를 위한 IT실무교육
[IT교육/IT학원]Develope를 위한 IT실무교육
 
[아이오닉학원]아이오닉 하이브리드 앱 개발 과정(아이오닉2로 동적 모바일 앱 만들기)
[아이오닉학원]아이오닉 하이브리드 앱 개발 과정(아이오닉2로 동적 모바일 앱 만들기)[아이오닉학원]아이오닉 하이브리드 앱 개발 과정(아이오닉2로 동적 모바일 앱 만들기)
[아이오닉학원]아이오닉 하이브리드 앱 개발 과정(아이오닉2로 동적 모바일 앱 만들기)
 
[뷰제이에스학원]뷰제이에스(Vue.js) 프로그래밍 입문(프로그레시브 자바스크립트 프레임워크)
[뷰제이에스학원]뷰제이에스(Vue.js) 프로그래밍 입문(프로그레시브 자바스크립트 프레임워크)[뷰제이에스학원]뷰제이에스(Vue.js) 프로그래밍 입문(프로그레시브 자바스크립트 프레임워크)
[뷰제이에스학원]뷰제이에스(Vue.js) 프로그래밍 입문(프로그레시브 자바스크립트 프레임워크)
 
[씨샵학원/씨샵교육]C#, 윈폼, 네트워크, ado.net 실무프로젝트 과정
[씨샵학원/씨샵교육]C#, 윈폼, 네트워크, ado.net 실무프로젝트 과정[씨샵학원/씨샵교육]C#, 윈폼, 네트워크, ado.net 실무프로젝트 과정
[씨샵학원/씨샵교육]C#, 윈폼, 네트워크, ado.net 실무프로젝트 과정
 
[정보처리기사자격증학원]정보처리기사 취득 양성과정(국비무료 자격증과정)
[정보처리기사자격증학원]정보처리기사 취득 양성과정(국비무료 자격증과정)[정보처리기사자격증학원]정보처리기사 취득 양성과정(국비무료 자격증과정)
[정보처리기사자격증학원]정보처리기사 취득 양성과정(국비무료 자격증과정)
 
[wpf학원,wpf교육]닷넷, c#기반 wpf 프로그래밍 인터페이스구현 재직자 향상과정
[wpf학원,wpf교육]닷넷, c#기반 wpf 프로그래밍 인터페이스구현 재직자 향상과정[wpf학원,wpf교육]닷넷, c#기반 wpf 프로그래밍 인터페이스구현 재직자 향상과정
[wpf학원,wpf교육]닷넷, c#기반 wpf 프로그래밍 인터페이스구현 재직자 향상과정
 
(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...
(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...
(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...
 
[자마린교육/자마린실습]자바,스프링프레임워크(스프링부트) RESTful 웹서비스 구현 실습,자마린에서 스프링 웹서비스를 호출하고 응답 JS...
[자마린교육/자마린실습]자바,스프링프레임워크(스프링부트) RESTful 웹서비스 구현 실습,자마린에서 스프링 웹서비스를 호출하고 응답 JS...[자마린교육/자마린실습]자바,스프링프레임워크(스프링부트) RESTful 웹서비스 구현 실습,자마린에서 스프링 웹서비스를 호출하고 응답 JS...
[자마린교육/자마린실습]자바,스프링프레임워크(스프링부트) RESTful 웹서비스 구현 실습,자마린에서 스프링 웹서비스를 호출하고 응답 JS...
 
[구로자마린학원/자마린강좌/자마린교육]3. xamarin.ios 3.3.5 추가적인 사항
[구로자마린학원/자마린강좌/자마린교육]3. xamarin.ios  3.3.5 추가적인 사항[구로자마린학원/자마린강좌/자마린교육]3. xamarin.ios  3.3.5 추가적인 사항
[구로자마린학원/자마린강좌/자마린교육]3. xamarin.ios 3.3.5 추가적인 사항
 
3. xamarin.i os 3.3 xamarin.ios helloworld 자세히 살펴보기 3.4.4 view controllers an...
3. xamarin.i os 3.3 xamarin.ios helloworld 자세히 살펴보기 3.4.4 view controllers an...3. xamarin.i os 3.3 xamarin.ios helloworld 자세히 살펴보기 3.4.4 view controllers an...
3. xamarin.i os 3.3 xamarin.ios helloworld 자세히 살펴보기 3.4.4 view controllers an...
 
5. 서브 쿼리(sub query) 5.1 서브 쿼리(sub query) 개요 5.2 단일행 서브쿼리(single row sub query)
5. 서브 쿼리(sub query) 5.1 서브 쿼리(sub query) 개요 5.2 단일행 서브쿼리(single row sub query)5. 서브 쿼리(sub query) 5.1 서브 쿼리(sub query) 개요 5.2 단일행 서브쿼리(single row sub query)
5. 서브 쿼리(sub query) 5.1 서브 쿼리(sub query) 개요 5.2 단일행 서브쿼리(single row sub query)
 
3. xamarin.i os 3.1 xamarin.ios 설치, 개발환경 3.2 xamarin.ios helloworld(단일 뷰) 실습[...
3. xamarin.i os 3.1 xamarin.ios 설치, 개발환경 3.2 xamarin.ios helloworld(단일 뷰) 실습[...3. xamarin.i os 3.1 xamarin.ios 설치, 개발환경 3.2 xamarin.ios helloworld(단일 뷰) 실습[...
3. xamarin.i os 3.1 xamarin.ios 설치, 개발환경 3.2 xamarin.ios helloworld(단일 뷰) 실습[...
 
(닷넷,자마린,아이폰실습)Xamarin.iOS HelloWorld 실습_멀티화면,화면전환_Xamarin교육/Xamarin강좌
(닷넷,자마린,아이폰실습)Xamarin.iOS HelloWorld 실습_멀티화면,화면전환_Xamarin교육/Xamarin강좌(닷넷,자마린,아이폰실습)Xamarin.iOS HelloWorld 실습_멀티화면,화면전환_Xamarin교육/Xamarin강좌
(닷넷,자마린,아이폰실습)Xamarin.iOS HelloWorld 실습_멀티화면,화면전환_Xamarin교육/Xamarin강좌
 
C#기초에서 윈도우, 스마트폰 앱개발 과정(c#.net, ado.net, win form, wpf, 자마린)_자마린학원_씨샵교육_WPF학원...
C#기초에서 윈도우, 스마트폰 앱개발 과정(c#.net, ado.net, win form, wpf, 자마린)_자마린학원_씨샵교육_WPF학원...C#기초에서 윈도우, 스마트폰 앱개발 과정(c#.net, ado.net, win form, wpf, 자마린)_자마린학원_씨샵교육_WPF학원...
C#기초에서 윈도우, 스마트폰 앱개발 과정(c#.net, ado.net, win form, wpf, 자마린)_자마린학원_씨샵교육_WPF학원...
 
자바, 웹 기초와 스프링 프레임워크 & 마이바티스 재직자 향상과정(자바학원/자바교육/자바기업출강]
자바, 웹 기초와 스프링 프레임워크 & 마이바티스 재직자 향상과정(자바학원/자바교육/자바기업출강]자바, 웹 기초와 스프링 프레임워크 & 마이바티스 재직자 향상과정(자바학원/자바교육/자바기업출강]
자바, 웹 기초와 스프링 프레임워크 & 마이바티스 재직자 향상과정(자바학원/자바교육/자바기업출강]
 
3. xamarin.i os 3.1 xamarin.ios 설치, 개발환경 3.2 xamarin.ios helloworld_자마린학원_자마린...
3. xamarin.i os 3.1 xamarin.ios 설치, 개발환경 3.2 xamarin.ios helloworld_자마린학원_자마린...3. xamarin.i os 3.1 xamarin.ios 설치, 개발환경 3.2 xamarin.ios helloworld_자마린학원_자마린...
3. xamarin.i os 3.1 xamarin.ios 설치, 개발환경 3.2 xamarin.ios helloworld_자마린학원_자마린...
 
3. 안드로이드 애플리케이션 구성요소 3.2인텐트 part01(안드로이드학원/안드로이드교육/안드로이드강좌/안드로이드기업출강]
3. 안드로이드 애플리케이션 구성요소 3.2인텐트 part01(안드로이드학원/안드로이드교육/안드로이드강좌/안드로이드기업출강]3. 안드로이드 애플리케이션 구성요소 3.2인텐트 part01(안드로이드학원/안드로이드교육/안드로이드강좌/안드로이드기업출강]
3. 안드로이드 애플리케이션 구성요소 3.2인텐트 part01(안드로이드학원/안드로이드교육/안드로이드강좌/안드로이드기업출강]
 

(AngularJS,React를 위한 자바스크립트)getter, setter of class_AngularJS교육/ReactJS교육/자바스크립트교육추천

  • 1. { for AngularJS, React} 고급 자바스크립트 4. getter, setter ofclass 탑크리에듀 IT기술 칼럼 와 함께하는
  • 2. { ES6 }4. getter, setter of class 자바스크립트의 프로퍼티는 성질에 따라서 데이터 프로퍼티와 접근자 프로퍼티로 구분합니다. 이번 시간에는 접근자 프로퍼티와 관련된 얘기입니다. 이해를 돕기 위해서 예를 들어 보면, 자바언어에서 getter, setter 메소드는 로직을 위한 메소드가 아니라 객체가 갖고 있는 변수에 접근해서 값을 가져가거나 수정하 는 용도로 사용하는 메소드입니다. 부가적으로 값을 가공하는 로직정도를 두기도 합니다. 자바스크립트는 자바언어에서 지원하는 접근자(예: private, protected, public) 개념 이 없기 때문에 자바스크립트의 게터, 세터를 단지 프로퍼티의 값을 접근하거나 수 정하는 용도로 사용한다면 사실 큰 의미가 없습니다. 프로퍼티에 직접 접근해서 사용할 수 있기 때문이지요. 차라리, 자바스크립트의 게 터, 세터는 값을 조작해서 가져가거나 조작해서 수정하고자 하는 부가적인 로직을 두고 싶은 경우에 사용한다고 이해하시는게 좋겠습니다.
  • 3. { ES6 }4. getter, setter of class class4.es6 classCar{ constructor(name){ this.name= name; } get_name(){ returnthis.name; } set_name(name){ this.name= name; } } varcar= newCar('A'); console.log(car); //{ name:'A'} 자바스크립트는 클래스문법에서 get, set 키워드로 정의하는 함수 선언방법을 도입했습니다. 우선, 클래스 문법의 사용예제를 살펴보겠습니다.
  • 4. { ES6 }4. getter, setter of class console.log(Object.getOwnPropertyNames(Car.prototype)); //['constructor','_name'] console.log(Object.getOwnPropertyDescriptor(Car.prototype,'_name')); /* { get:[Function:get_name], set:[Function:set_name], enumerable:false, configurable:true} */ console.log(car._name);//getter //A car._name= 'B';// 할당연산자와같이사용하면setter console.log(car._name); //B 선언방법은 함수 앞에 get, set 키워드를 설정하는 것 입니다. get, set키워드가 붙은 함수명은 일반적으로 같은 이름을 사용합니다. 이렇게 선언된 게터, 세 터 메소드를 통해 객체가 갖고 있는 변수에 접근하는 것을 제어합니다. 다른 랭귀지에서의 게 터, 세터 메소드와 사용 용도는 같지만 이용하는 방법은 차이가 있습니다.
  • 5. { ES6 }4. getter, setter of class console.log(car._name);//getter //A car._name= 'B';// 할당연산자와같이사용하면setter console.log(car._name); //B 자바스크립트의 게터, 세터 메소드는 괄호없이 사용해야 합니다. 할당연산자가 없으면 게터로 작동하고 할당연산자와 같이 사용하면 세터로 작동합니다. console.log(Object.getOwnPropertyNames(Car.prototype)); //[ 'constructor','_name'] 자바스크립트의 게터, 세터 메소드는 생성자 함수의 프로토타입 객체에 추가되며 get, set 두 개의 함수는 결국 하나의 프로퍼티의 서술자 객체의 속성으로 반영되어 처리됩니다.
  • 6. { ES6 }4. getter, setter of class console.log(Object.getOwnPropertyDescriptor(Car.prototype,'_name')); /* { get:[Function:get_name], set:[Function:set_name], enumerable:false, configurable:true} */ 자바스크립트의 get, set 설정으로 추가된 프로퍼티는 접근자 프로퍼티입니다. get: 값을조회하는함수다.기본값은undefined이다. set:값을수정하는함수다.기본값은undefined이다. enumerable:for-in루프나Object.keys()메소드를사용하여열거할수있다. configurable:프로퍼티속성을변경,삭제할수있다. 접근자 프로퍼티의 속성을 정의하는 서술자 객체의 프로퍼티의 용도는 다음과 같습니다.
  • 7. { ES6 }4. getter, setter of class 이해를 돕기 위해서, 똑같은 결과를 얻을 수 있는 코드를 ES5 함수문법으로 작성해서 살펴보 겠습니다. functionCar(name){ this.name=name; } Object.defineProperty(Car.prototype,'_name',{ get:function(){ returnthis.name; }, set:function(name){ this.name= name; }, enumerable:false, configurable:true }); varcar= newCar('A'); console.log(car); //{ name:'A' } console.log(Object.getOwnPropertyNames(Car.prototype)); //[ 'constructor','_name'] example4.js
  • 8. { ES6 }4. getter, setter of class console.log(Object.getOwnPropertyDescriptor(Car.prototype,'_name')); /* { get:[Function:get_name], set:[Function:set_name], enumerable:false, configurable:true} */ console.log(car._name);//getter //A car._name= 'B';//할당연산자와같이사용하면setter console.log(car._name); //B 그런데, 객체의 변수 name에 직접 접근할 수 있는 데, 접근자 프로퍼티를 설정하여 get, set 함수를 둘 필요가 있을까요? get, set 함수에 부가적인 처리로직을 둔다면 의미가 생깁니다. 반대로 값을 가져가거나 수정할 때 처리하는 부가적인 로직이 없다면 접근자 프로퍼티를 둘 필요가 없습니다.
  • 9. { ES6 }4. getter, setter of class example4-2.js functionCar(name){ //this.name= name;// 아래코드로대체한다. Object.defineProperty(this,'name',{ value:name, writable:false, enumerable:true, configurable:true }); } 프로퍼티 서술자 객체를 사용하여 새로 만들어지는 객체에 프로퍼티 ‘name’을 추가합니다. 이 때, 프로퍼티 속성 중 writable 값을 false로 선언합니다. 이러면 이 프로퍼티의 값은 변경할 수 없게 됩니다. 그래서, 다음과 같은 현상이 벌어집니다. “car._name=’B’” 처럼 세터를 사용하여도 “car.name=’B’” 처럼 직접 프로퍼티를 수정하려고 시도하여도 변경되지 않으며 예외도 발생하지 않습니다. 값이 변경되지 않는데 예외가 발생하지 않는군요!
  • 10. { ES6 }4. getter, setter of class console.log(car._name); //A car._name= 'B'; console.log(car._name); //A 세터를 사용하는 경우 다음처럼 예외를 던져 친절하게 수정할 수 없다고 알려 줄 수 있습니다. Object.defineProperty(Car.prototype,'_name',{ get:function(){ returnthis.name; }, //set:function(name){ //아래코드로대체한다. // this.name=name; //}, set:function(name){ thrownewError('값을변경할수없습니다.'); }, enumerable:false, configurable:true });
  • 11. { ES6 }4. getter, setter of class 그러나, 사용자가 세터를 통해서 값에 접근하지 않고 직접 값을 갖고 있는 프로퍼티에 접근할 수 있기 때문에 완전한 해결책은 아닙니다. 따라서, 데이터 프로퍼티 접근 시 무언가 로직을 수행하여 사용자에게 알려줄 수 있는 방법이 필요하다는 결론에 다다르게 됩니다. 이 때, 프록시 객체의 필요성이 대두됩니다. 아래 example4-3.js에서 사용방법을 살펴보겠습니 다. 다음은 테스트를 위해 변경한 전체 소스코드입니다. example4-2.js functionCar(name){ //this.name= name; Object.defineProperty(this,'name',{ value:name, writable:false, enumerable:true, configurable:true }); }
  • 12. { ES6 }4. getter, setter of class Object.defineProperty(Car.prototype,'_name',{ get:function(){ returnthis.name; }, //set:function(name){ // this.name=name; //}, set:function(name){ thrownewError('값을변경할수없습니다.'); }, enumerable:false, configurable:true }); varcar= newCar('A'); console.log(car); //{ name:'A'} console.log(Object.getOwnPropertyNames(Car.prototype)); //[ 'constructor','_name'] console.log(Object.getOwnPropertyDescriptor(Car.prototype,'_name'));
  • 13. { ES6 }4. getter, setter of class /* { get:[Function:get_name], set:[Function:set_name], enumerable:false, configurable:true} */ console.log(car._name);//getter //A try{ car._name= 'B';//할당연산자와같이사용하면setter } catch(e) { console.log('catch>>'+ e.name); console.log('catch>>'+ e.message); } console.log(car._name); //A
  • 14. { ES6 }4. getter, setter of class 다음은 데이터 프로퍼티 name의 서술자 속성 중, “writable: false” 설정으로 값을 변경할 수 없 으므로 이를 사용자에게 알려주기위한 설정방법입니다. example4-3.js functionCar(name,color){ Object.defineProperty(this,'name',{ value:name, writable:false, enumerable:true, configurable:true }); this.color=color; } varcar= newCar('A','White'); console.log(car); //{ name:'A',color:'White'} console.log(car.name); //A car.name='B'; //writable:false설정으로변경되지않지만,예외도발생하지않는다. console.log(car.name); //A
  • 15. { ES6 }4. getter, setter of class varhandler= { set:function(target,property,value,receiver){ if(property=== 'name'){ thrownewError('name프로퍼티는변경할수 없습니다.') } //처리되어야하는원래로직을수행한다. target[property]= value; } }; varproxyCar= newProxy(car,handler); //사용자에게car 객체대신proxyCar객체를주면 //사용자가프로퍼티를변경하고자하는경우 //set트랩이기동한다. try{ proxyCar.name='B'; } catch(e) { console.log(e.message); //name프로퍼티는변경할수없습니다. } proxyCar.color='Red'; console.log(car); //{ name:'A',color:'Red'}
  • 16. { ES6 }4. getter, setter of class 원래 값을 갖고 있는 car 객체가 target입니다. 이를 프록시 객체로 감싼 객체를 변수 proxyCar 가 가리킵니다. 타겟 객체에 접근하기 전 프록시객체 생성 시 설정한 handler 객체의 트랩함수가 기동합니다. 이 때, “writable: false”로 설정된 name 프로퍼티를 수정하고 하는 경우 예외를 발생시켜 사용 자에게 알려주는 방식입니다. 이번 시간의 주제로 돌아옵니다. 자바스크립트의 객체 프로퍼티는 두 가지 용도로 사용될 수 있다는 것을 기억하시면 좋겠습니다. 1. 데이터 프로퍼티 : 변수, 함수를 보관한다. 2. 접근자 프로퍼티 : 변수, 함수의 접근 시 부가적인 작업을 수행한 후 데이터 프로퍼티와 연계한다. 객체 프로퍼티의 두 가지 용도
  • 17. { ES6 }4. getter, setter of class 게터, 세터의 필요성 및 서술자 속성의 역할이 무엇인지 파악할 수 있는 예제를 살펴보면서 마 치도록 하겠습니다. example-configurable.js varperson={}; Object.defineProperty(person,'name',{ value:'B', writable:true, enumerable:true, configurable:false }); console.log(Object.getOwnPropertyDescriptor(person,'name')); //{ value:'B', // writable:true, // enumerable:true, // configurable:true}
  • 18. { ES6 }4. getter, setter of class console.log(person); //{ name:'B'} person.name= 'A'; console.log(person); //{ name:'A'} deleteperson.name;//configurable:false설정으로삭제되지않는다. console.log(Object.getOwnPropertyDescriptor(person,'name')); //{ value:'A', // writable:true, // enumerable:true, // configurable:false} “delete person.name;” 코드는 name 프로퍼티의 서술자 설정 중, “configurable: false” 설정으 로 삭제되지 않습니다.
  • 19. { ES6 }4. getter, setter of class example-needs-get-set.js varperson={}; person.firstName='Tom'; person.lastName= 'Cruise'; console.log(person); //{ firstName:'Tom',lastName:'Cruise'} Object.defineProperty(person,'fullName',{ get:function(){ returnthis.firstName+ '' +this.lastName; }, set:function(fullName){ varnames= fullName.split(''); this.firstName=names[0]; this.lastName= names[1]; }, enumerable:false, configurable:true });
  • 20. { ES6 }4. getter, setter of class //enumerable:false설정으로fullName접근자프로퍼티는보이지않는다. console.log(person); //{ firstName:'Tom',lastName:'Cruise'} console.log(person.fullName);// 게터 //Tom Cruise person.fullName='BradPitt';// 세터 console.log(person.fullName); //BradPitt person 객체의 fullName 프로퍼티의 서술자 설정 중, “enumerable: false”로 설정했으므로 “console.log(person);” 코드로는 fullName 프로퍼티가 포함되지 않습니다.
  • 21. { ES6 }4. getter, setter of class 송석원 현재 : - 탑크리에듀교육센터 자바, 스프링 프레임워크, JPA, Querydsl, AngularJS, React, Android 분야 전임강사 경력 : - 오라클자바커뮤니티교육센터 자바, 스프링, JPA, Node.JS, AngularJS, React, Android 전임강사 - 탑크리에듀 교육센터 Java, Spring Data JPA, Querydsl, SQL 교재 편찬위원 - 회원수 14,000명의 오라클자바커뮤니티 운영 및 관리 - SK T-아카데미 스프링 프레임워크 강의 - 정철 어학원 탑크리에듀교육센터 Tel. 02-851-4790 http://www.topcredu.co.kr Copyrights ⓒ Topcredu. All rights Reserved.