SlideShare a Scribd company logo
1 of 21
Download to read offline
{ for AngularJS, React}
고급 자바스크립트
4. getter, setter of class
탑크리에듀
IT기술
4. getter, setter of class
자바스크립트의 프로퍼티는 성질에 따라서 데이터 프로퍼티와 접근자 프로퍼티로
구분합니다. 이번 시간에는 접근자 프로퍼티와 관련된 얘기입니다.
이해를 돕기 위해서 예를 들어 보면, 자바얶어에서 getter, setter 메소드는 로직을
위핚 메소드가 아니라 객체가 갖고 있는 변수에 접근해서 값을 가져가거나 수정하
는 용도로 사용하는 메소드입니다.
부가적으로 값을 가공하는 로직정도를 두기도 합니다.
자바스크립트는 자바얶어에서 지원하는 접근자(예: private, protected, public) 개념
이 없기 때문에 자바스크립트의 게터, 세터를 단지 프로퍼티의 값을 접근하거나 수
정하는 용도로 사용핚다면 사실 큰 의미가 없습니다.
프로퍼티에 직접 접근해서 사용핛 수 있기 때문이지요. 차라리, 자바스크립트의 게
터, 세터는 값을 조작해서 가져가거나 조작해서 수정하고자 하는 부가적인 로직을
두고 싶은 경우에 사용핚다고 이해하시는게 좋겠습니다.
4. getter, setter of class
class4.es6
class Car {
constructor(name) {
this.name = name;
}
get _name() {
return this.name;
}
set _name(name) {
this.name = name;
}
}
var car = new Car('A');
console.log(car);
// { name: 'A' }
자바스크립트는 클래스문법에서 get, set 키워드로 정의하는 함수 선얶방법을 도입했습니다.
우선, 클래스 문법의 사용예제를 살펴보겠습니다.
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키워드가 붙은 함수명은 일반적으로 같은 이름을 사용합니다. 이렇게 선얶된 게터, 세
터 메소드를 통해 객체가 갖고 있는 변수에 접근하는 것을 제어합니다. 다른 랭귀지에서의 게
터, 세터 메소드와 사용 용도는 같지만 이용하는 방법은 차이가 있습니다.
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 두
개의 함수는 결국 하나의 프로퍼티의 서술자 객체의 속성으로 반영되어 처리됩니다.
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 : 프로퍼티 속성을 변경, 삭제핛 수 있다.
접근자 프로퍼티의 속성을 정의하는 서술자 객체의 프로퍼티의 용도는 다음과 같습니다.
4. getter, setter of class
이해를 돕기 위해서, 똑같은 결과를 얻을 수 있는 코드를 ES5 함수문법으로 작성해서 살펴보
겠습니다.
function Car(name) {
this.name = name;
}
Object.defineProperty(Car.prototype, '_name', {
get: function() {
return this.name;
},
set: function(name) {
this.name = name;
},
enumerable: false,
configurable: true
});
var car = new Car('A');
console.log(car);
// { name: 'A' }
console.log(Object.getOwnPropertyNames(Car.prototype));
// [ 'constructor', '_name' ]
example4.js
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 함수에 부가적인 처리로직을 둔다면 의미가 생깁니다.
반대로 값을 가져가거나 수정핛 때 처리하는 부가적인 로직이 없다면 접근자 프로퍼티를 둘
필요가 없습니다.
4. getter, setter of class
example4-2.js
function Car(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‟” 처럼 직접 프로퍼티를 수정하려고
시도하여도 변경되지 않으며 예외도 발생하지 않습니다.
값이 변경되지 않는데 예외가 발생하지 않는굮요!
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() {
return this.name;
},
// set: function(name) { // 아래 코드로 대체핚다.
// this.name = name;
// },
set: function(name) {
throw new Error('값을 변경핛 수 없습니다.');
},
enumerable: false,
configurable: true
});
4. getter, setter of class
그러나, 사용자가 세터를 통해서 값에 접근하지 않고 직접 값을 갖고 있는 프로퍼티에 접근핛
수 있기 때문에 완전핚 해결책은 아닙니다. 따라서, 데이터 프로퍼티 접근 시 무얶가 로직을
수행하여 사용자에게 알려줄 수 있는 방법이 필요하다는 결롞에 다다르게 됩니다.
이 때, 프록시 객체의 필요성이 대두됩니다. 아래 example4-3.js에서 사용방법을 살펴보겠습니
다.
다음은 테스트를 위해 변경핚 전체 소스코드입니다.
example4-2.js
function Car(name) {
// this.name = name;
Object.defineProperty(this, 'name', {
value: name,
writable: false,
enumerable: true,
configurable: true
});
}
4. getter, setter of class
Object.defineProperty(Car.prototype, '_name', {
get: function() {
return this.name;
},
// set: function(name) {
// this.name = name;
// },
set: function(name) {
throw new Error('값을 변경핛 수 없습니다.');
},
enumerable: false,
configurable: true
});
var car = new Car('A');
console.log(car);
// { name: 'A' }
console.log(Object.getOwnPropertyNames(Car.prototype));
// [ 'constructor', '_name' ]
console.log(Object.getOwnPropertyDescriptor(Car.prototype, '_name'));
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
4. getter, setter of class
다음은 데이터 프로퍼티 name의 서술자 속성 중, “writable: false” 설정으로 값을 변경핛 수 없
으므로 이를 사용자에게 알려주기위핚 설정방법입니다.
example4-3.js
function Car(name, color) {
Object.defineProperty(this, 'name', {
value: name,
writable: false,
enumerable: true,
configurable: true
});
this.color = color;
}
var car = new Car('A', 'White');
console.log(car);
// { name: 'A', color: 'White' }
console.log(car.name);
// A
car.name = 'B';
// writable: false 설정으로 변경되지 않지만, 예외도 발생하지 않는다.
console.log(car.name);
// A
4. getter, setter of class
var handler = {
set: function(target, property, value, receiver) {
if (property === 'name') {
throw new Error('name 프로퍼티는 변경핛 수 없습니다.')
}
// 처리되어야 하는 원래 로직을 수행핚다.
target[property] = value;
}
};
var proxyCar = new Proxy(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' }
4. getter, setter of class
원래 값을 갖고 있는 car 객체가 target입니다. 이를 프록시 객체로 감싼 객체를 변수 proxyCar
가 가리킵니다.
타겟 객체에 접근하기 전 프록시객체 생성 시 설정핚 handler 객체의 트랩함수가 기동합니다.
이 때, “writable: false”로 설정된 name 프로퍼티를 수정하고 하는 경우 예외를 발생시켜 사용
자에게 알려주는 방식입니다.
이번 시간의 주제로 돌아옵니다. 자바스크립트의 객체 프로퍼티는 두 가지 용도로 사용될 수
있다는 것을 기억하시면 좋겠습니다.
1. 데이터 프로퍼티 : 변수, 함수를 보관핚다.
2. 접근자 프로퍼티 : 변수, 함수의 접근 시 부가적인 작업을 수행핚 후 데이터 프로퍼티와 연계핚다.
객체 프로퍼티의 두 가지 용도
4. getter, setter of class
게터, 세터의 필요성 및 서술자 속성의 역핛이 무엇인지 파악핛 수 있는 예제를 살펴보면서 마
치도록 하겠습니다.
example-configurable.js
var person = {};
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 }
4. getter, setter of class
console.log(person);
// { name: 'B' }
person.name = 'A';
console.log(person);
// { name: 'A' }
delete person.name; // configurable: false 설정으로 삭제되지 않는다.
console.log(Object.getOwnPropertyDescriptor(person, 'name'));
// { value: 'A',
// writable: true,
// enumerable: true,
// configurable: false }
“delete person.name;” 코드는 name 프로퍼티의 서술자 설정 중, “configurable: false” 설정으
로 삭제되지 않습니다.
4. getter, setter of class
example-needs-get-set.js
var person = {};
person.firstName = 'Tom';
person.lastName = 'Cruise';
console.log(person);
// { firstName: 'Tom', lastName: 'Cruise' }
Object.defineProperty(person, 'fullName', {
get: function() {
return this.firstName + ' ' + this.lastName;
},
set: function(fullName) {
var names = fullName.split(' ');
this.firstName = names[0];
this.lastName = names[1];
},
enumerable: false,
configurable: true
});
4. getter, setter of class
// enumerable: false 설정으로 fullName 접근자 프로퍼티는 보이지 않는다.
console.log(person);
// { firstName: 'Tom', lastName: 'Cruise' }
console.log(person.fullName); // 게터
// Tom Cruise
person.fullName = 'Brad Pitt'; // 세터
console.log(person.fullName);
// Brad Pitt
person 객체의 fullName 프로퍼티의 서술자 설정 중, “enumerable: false”로 설정했으므로
“console.log(person);” 코드로는 fullName 프로퍼티가 포함되지 않습니다.
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.

More Related Content

What's hot

9 object class
9 object class9 object class
9 object class웅식 전
 
Javascript 완벽 가이드 정리
Javascript 완벽 가이드 정리Javascript 완벽 가이드 정리
Javascript 완벽 가이드 정리ETRIBE_STG
 
자바스크립트 기초문법~함수기초
자바스크립트 기초문법~함수기초자바스크립트 기초문법~함수기초
자바스크립트 기초문법~함수기초진수 정
 
Cpp에서 활용해보는 Lambda식
Cpp에서 활용해보는 Lambda식Cpp에서 활용해보는 Lambda식
Cpp에서 활용해보는 Lambda식TonyCms
 
이펙티브 C++ 5,6 장 스터디
이펙티브 C++ 5,6 장 스터디이펙티브 C++ 5,6 장 스터디
이펙티브 C++ 5,6 장 스터디quxn6
 
Effective cpp
Effective cppEffective cpp
Effective cppTonyCms
 
프론트엔드스터디 E03 - Javascript intro.
프론트엔드스터디 E03 - Javascript intro.프론트엔드스터디 E03 - Javascript intro.
프론트엔드스터디 E03 - Javascript intro.Young-Beom Rhee
 
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
 
Effective c++ Chapter1,2
Effective c++ Chapter1,2Effective c++ Chapter1,2
Effective c++ Chapter1,2문익 장
 
C#을 사용한 빠른 툴 개발
C#을 사용한 빠른 툴 개발C#을 사용한 빠른 툴 개발
C#을 사용한 빠른 툴 개발흥배 최
 
이펙티브 C++ 스터디
이펙티브 C++ 스터디이펙티브 C++ 스터디
이펙티브 C++ 스터디quxn6
 
호이스팅, 클로저, IIFE
호이스팅, 클로저, IIFE호이스팅, 클로저, IIFE
호이스팅, 클로저, IIFEChangHyeon Bae
 
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
 
Multithread programming 20151206_서진택
Multithread programming 20151206_서진택Multithread programming 20151206_서진택
Multithread programming 20151206_서진택JinTaek Seo
 
이펙티브 C++ (7~9)
이펙티브 C++ (7~9)이펙티브 C++ (7~9)
이펙티브 C++ (7~9)익성 조
 
Hacosa js study 2주차
Hacosa js study 2주차Hacosa js study 2주차
Hacosa js study 2주차Seong Bong Ji
 

What's hot (20)

9 object class
9 object class9 object class
9 object class
 
Javascript 완벽 가이드 정리
Javascript 완벽 가이드 정리Javascript 완벽 가이드 정리
Javascript 완벽 가이드 정리
 
자바스크립트 기초문법~함수기초
자바스크립트 기초문법~함수기초자바스크립트 기초문법~함수기초
자바스크립트 기초문법~함수기초
 
Cpp에서 활용해보는 Lambda식
Cpp에서 활용해보는 Lambda식Cpp에서 활용해보는 Lambda식
Cpp에서 활용해보는 Lambda식
 
이펙티브 C++ 5,6 장 스터디
이펙티브 C++ 5,6 장 스터디이펙티브 C++ 5,6 장 스터디
이펙티브 C++ 5,6 장 스터디
 
Effective cpp
Effective cppEffective cpp
Effective cpp
 
프론트엔드스터디 E03 - Javascript intro.
프론트엔드스터디 E03 - Javascript intro.프론트엔드스터디 E03 - Javascript intro.
프론트엔드스터디 E03 - Javascript intro.
 
C++에서 Objective-C까지
C++에서 Objective-C까지C++에서 Objective-C까지
C++에서 Objective-C까지
 
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
 
Effective c++ Chapter1,2
Effective c++ Chapter1,2Effective c++ Chapter1,2
Effective c++ Chapter1,2
 
C#을 사용한 빠른 툴 개발
C#을 사용한 빠른 툴 개발C#을 사용한 빠른 툴 개발
C#을 사용한 빠른 툴 개발
 
이펙티브 C++ 스터디
이펙티브 C++ 스터디이펙티브 C++ 스터디
이펙티브 C++ 스터디
 
호이스팅, 클로저, IIFE
호이스팅, 클로저, IIFE호이스팅, 클로저, IIFE
호이스팅, 클로저, IIFE
 
Java 8 api :: lambda 이용하기
Java 8 api :: lambda 이용하기Java 8 api :: lambda 이용하기
Java 8 api :: lambda 이용하기
 
Lambda 란 무엇인가
Lambda 란 무엇인가Lambda 란 무엇인가
Lambda 란 무엇인가
 
Multithread programming 20151206_서진택
Multithread programming 20151206_서진택Multithread programming 20151206_서진택
Multithread programming 20151206_서진택
 
이펙티브 C++ (7~9)
이펙티브 C++ (7~9)이펙티브 C++ (7~9)
이펙티브 C++ (7~9)
 
javascript01
javascript01javascript01
javascript01
 
Hacosa js study 2주차
Hacosa js study 2주차Hacosa js study 2주차
Hacosa js study 2주차
 
5 swift 기초함수
5 swift 기초함수5 swift 기초함수
5 swift 기초함수
 

Similar to [IT기술칼럼 #4] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원

(고급자바스크립트강좌 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 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
 
파이썬 모듈 패키지
파이썬 모듈 패키지파이썬 모듈 패키지
파이썬 모듈 패키지SeongHyun Ahn
 
파이썬+주요+용어+정리 20160304
파이썬+주요+용어+정리 20160304파이썬+주요+용어+정리 20160304
파이썬+주요+용어+정리 20160304Yong Joon Moon
 
게임프로그래밍입문 7
게임프로그래밍입문 7게임프로그래밍입문 7
게임프로그래밍입문 7Yeonah Ki
 
C# 세미나 12회차
C# 세미나 12회차C# 세미나 12회차
C# 세미나 12회차Jeung_mh
 
[2011 04 11]mock_object 소개
[2011 04 11]mock_object 소개[2011 04 11]mock_object 소개
[2011 04 11]mock_object 소개Jong Pil Won
 
Refactoring - Chapter 8.2
Refactoring - Chapter 8.2Refactoring - Chapter 8.2
Refactoring - Chapter 8.2Ji Ung Lee
 
Role Of Server In Ajax Korean
Role Of Server In Ajax KoreanRole Of Server In Ajax Korean
Role Of Server In Ajax KoreanTerry Cho
 
프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oopYoung-Beom Rhee
 
생코자바스크립트스터디3장
생코자바스크립트스터디3장생코자바스크립트스터디3장
생코자바스크립트스터디3장Jinhwa Hong
 
Es2015 Simple Overview
Es2015 Simple OverviewEs2015 Simple Overview
Es2015 Simple OverviewKim Hunmin
 
[아꿈사] The C++ Programming Language 11장 연산자 오버로딩
[아꿈사] The C++ Programming Language 11장 연산자 오버로딩[아꿈사] The C++ Programming Language 11장 연산자 오버로딩
[아꿈사] The C++ Programming Language 11장 연산자 오버로딩해강
 
ECMA Script 5 & 6
ECMA Script 5 & 6ECMA Script 5 & 6
ECMA Script 5 & 6sewoo lee
 
예제로 맛보는 Backbone 연습
예제로 맛보는 Backbone 연습예제로 맛보는 Backbone 연습
예제로 맛보는 Backbone 연습은숙 이
 
08장 객체와 클래스 (기본)
08장 객체와 클래스 (기본)08장 객체와 클래스 (기본)
08장 객체와 클래스 (기본)유석 남
 
Django admin site 커스텀하여 적극적으로 활용하기
Django admin site 커스텀하여 적극적으로 활용하기Django admin site 커스텀하여 적극적으로 활용하기
Django admin site 커스텀하여 적극적으로 활용하기영우 박
 

Similar to [IT기술칼럼 #4] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원 (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 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
 
파이썬 모듈 패키지
파이썬 모듈 패키지파이썬 모듈 패키지
파이썬 모듈 패키지
 
파이썬+주요+용어+정리 20160304
파이썬+주요+용어+정리 20160304파이썬+주요+용어+정리 20160304
파이썬+주요+용어+정리 20160304
 
게임프로그래밍입문 7
게임프로그래밍입문 7게임프로그래밍입문 7
게임프로그래밍입문 7
 
C# 세미나 12회차
C# 세미나 12회차C# 세미나 12회차
C# 세미나 12회차
 
[2011 04 11]mock_object 소개
[2011 04 11]mock_object 소개[2011 04 11]mock_object 소개
[2011 04 11]mock_object 소개
 
Refactoring - Chapter 8.2
Refactoring - Chapter 8.2Refactoring - Chapter 8.2
Refactoring - Chapter 8.2
 
Role Of Server In Ajax Korean
Role Of Server In Ajax KoreanRole Of Server In Ajax Korean
Role Of Server In Ajax Korean
 
프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop
 
생코자바스크립트스터디3장
생코자바스크립트스터디3장생코자바스크립트스터디3장
생코자바스크립트스터디3장
 
Es2015 Simple Overview
Es2015 Simple OverviewEs2015 Simple Overview
Es2015 Simple Overview
 
[아꿈사] The C++ Programming Language 11장 연산자 오버로딩
[아꿈사] The C++ Programming Language 11장 연산자 오버로딩[아꿈사] The C++ Programming Language 11장 연산자 오버로딩
[아꿈사] The C++ Programming Language 11장 연산자 오버로딩
 
ECMA Script 5 & 6
ECMA Script 5 & 6ECMA Script 5 & 6
ECMA Script 5 & 6
 
Javascript
JavascriptJavascript
Javascript
 
예제로 맛보는 Backbone 연습
예제로 맛보는 Backbone 연습예제로 맛보는 Backbone 연습
예제로 맛보는 Backbone 연습
 
08장 객체와 클래스 (기본)
08장 객체와 클래스 (기본)08장 객체와 클래스 (기본)
08장 객체와 클래스 (기본)
 
Django admin site 커스텀하여 적극적으로 활용하기
Django admin site 커스텀하여 적극적으로 활용하기Django admin site 커스텀하여 적극적으로 활용하기
Django admin site 커스텀하여 적극적으로 활용하기
 
Xe hack
Xe hackXe hack
Xe hack
 

More from 탑크리에듀(구로디지털단지역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분거리)
 

More from 탑크리에듀(구로디지털단지역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(안드로이드학원/안드로이드교육/안드로이드강좌/안드로이드기업출강]
 

[IT기술칼럼 #4] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원

  • 1. { for AngularJS, React} 고급 자바스크립트 4. getter, setter of class 탑크리에듀 IT기술
  • 2. 4. getter, setter of class 자바스크립트의 프로퍼티는 성질에 따라서 데이터 프로퍼티와 접근자 프로퍼티로 구분합니다. 이번 시간에는 접근자 프로퍼티와 관련된 얘기입니다. 이해를 돕기 위해서 예를 들어 보면, 자바얶어에서 getter, setter 메소드는 로직을 위핚 메소드가 아니라 객체가 갖고 있는 변수에 접근해서 값을 가져가거나 수정하 는 용도로 사용하는 메소드입니다. 부가적으로 값을 가공하는 로직정도를 두기도 합니다. 자바스크립트는 자바얶어에서 지원하는 접근자(예: private, protected, public) 개념 이 없기 때문에 자바스크립트의 게터, 세터를 단지 프로퍼티의 값을 접근하거나 수 정하는 용도로 사용핚다면 사실 큰 의미가 없습니다. 프로퍼티에 직접 접근해서 사용핛 수 있기 때문이지요. 차라리, 자바스크립트의 게 터, 세터는 값을 조작해서 가져가거나 조작해서 수정하고자 하는 부가적인 로직을 두고 싶은 경우에 사용핚다고 이해하시는게 좋겠습니다.
  • 3. 4. getter, setter of class class4.es6 class Car { constructor(name) { this.name = name; } get _name() { return this.name; } set _name(name) { this.name = name; } } var car = new Car('A'); console.log(car); // { name: 'A' } 자바스크립트는 클래스문법에서 get, set 키워드로 정의하는 함수 선얶방법을 도입했습니다. 우선, 클래스 문법의 사용예제를 살펴보겠습니다.
  • 4. 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. 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. 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. 4. getter, setter of class 이해를 돕기 위해서, 똑같은 결과를 얻을 수 있는 코드를 ES5 함수문법으로 작성해서 살펴보 겠습니다. function Car(name) { this.name = name; } Object.defineProperty(Car.prototype, '_name', { get: function() { return this.name; }, set: function(name) { this.name = name; }, enumerable: false, configurable: true }); var car = new Car('A'); console.log(car); // { name: 'A' } console.log(Object.getOwnPropertyNames(Car.prototype)); // [ 'constructor', '_name' ] example4.js
  • 8. 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. 4. getter, setter of class example4-2.js function Car(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. 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() { return this.name; }, // set: function(name) { // 아래 코드로 대체핚다. // this.name = name; // }, set: function(name) { throw new Error('값을 변경핛 수 없습니다.'); }, enumerable: false, configurable: true });
  • 11. 4. getter, setter of class 그러나, 사용자가 세터를 통해서 값에 접근하지 않고 직접 값을 갖고 있는 프로퍼티에 접근핛 수 있기 때문에 완전핚 해결책은 아닙니다. 따라서, 데이터 프로퍼티 접근 시 무얶가 로직을 수행하여 사용자에게 알려줄 수 있는 방법이 필요하다는 결롞에 다다르게 됩니다. 이 때, 프록시 객체의 필요성이 대두됩니다. 아래 example4-3.js에서 사용방법을 살펴보겠습니 다. 다음은 테스트를 위해 변경핚 전체 소스코드입니다. example4-2.js function Car(name) { // this.name = name; Object.defineProperty(this, 'name', { value: name, writable: false, enumerable: true, configurable: true }); }
  • 12. 4. getter, setter of class Object.defineProperty(Car.prototype, '_name', { get: function() { return this.name; }, // set: function(name) { // this.name = name; // }, set: function(name) { throw new Error('값을 변경핛 수 없습니다.'); }, enumerable: false, configurable: true }); var car = new Car('A'); console.log(car); // { name: 'A' } console.log(Object.getOwnPropertyNames(Car.prototype)); // [ 'constructor', '_name' ] console.log(Object.getOwnPropertyDescriptor(Car.prototype, '_name'));
  • 13. 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. 4. getter, setter of class 다음은 데이터 프로퍼티 name의 서술자 속성 중, “writable: false” 설정으로 값을 변경핛 수 없 으므로 이를 사용자에게 알려주기위핚 설정방법입니다. example4-3.js function Car(name, color) { Object.defineProperty(this, 'name', { value: name, writable: false, enumerable: true, configurable: true }); this.color = color; } var car = new Car('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. 4. getter, setter of class var handler = { set: function(target, property, value, receiver) { if (property === 'name') { throw new Error('name 프로퍼티는 변경핛 수 없습니다.') } // 처리되어야 하는 원래 로직을 수행핚다. target[property] = value; } }; var proxyCar = new Proxy(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. 4. getter, setter of class 원래 값을 갖고 있는 car 객체가 target입니다. 이를 프록시 객체로 감싼 객체를 변수 proxyCar 가 가리킵니다. 타겟 객체에 접근하기 전 프록시객체 생성 시 설정핚 handler 객체의 트랩함수가 기동합니다. 이 때, “writable: false”로 설정된 name 프로퍼티를 수정하고 하는 경우 예외를 발생시켜 사용 자에게 알려주는 방식입니다. 이번 시간의 주제로 돌아옵니다. 자바스크립트의 객체 프로퍼티는 두 가지 용도로 사용될 수 있다는 것을 기억하시면 좋겠습니다. 1. 데이터 프로퍼티 : 변수, 함수를 보관핚다. 2. 접근자 프로퍼티 : 변수, 함수의 접근 시 부가적인 작업을 수행핚 후 데이터 프로퍼티와 연계핚다. 객체 프로퍼티의 두 가지 용도
  • 17. 4. getter, setter of class 게터, 세터의 필요성 및 서술자 속성의 역핛이 무엇인지 파악핛 수 있는 예제를 살펴보면서 마 치도록 하겠습니다. example-configurable.js var person = {}; 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. 4. getter, setter of class console.log(person); // { name: 'B' } person.name = 'A'; console.log(person); // { name: 'A' } delete person.name; // configurable: false 설정으로 삭제되지 않는다. console.log(Object.getOwnPropertyDescriptor(person, 'name')); // { value: 'A', // writable: true, // enumerable: true, // configurable: false } “delete person.name;” 코드는 name 프로퍼티의 서술자 설정 중, “configurable: false” 설정으 로 삭제되지 않습니다.
  • 19. 4. getter, setter of class example-needs-get-set.js var person = {}; person.firstName = 'Tom'; person.lastName = 'Cruise'; console.log(person); // { firstName: 'Tom', lastName: 'Cruise' } Object.defineProperty(person, 'fullName', { get: function() { return this.firstName + ' ' + this.lastName; }, set: function(fullName) { var names = fullName.split(' '); this.firstName = names[0]; this.lastName = names[1]; }, enumerable: false, configurable: true });
  • 20. 4. getter, setter of class // enumerable: false 설정으로 fullName 접근자 프로퍼티는 보이지 않는다. console.log(person); // { firstName: 'Tom', lastName: 'Cruise' } console.log(person.fullName); // 게터 // Tom Cruise person.fullName = 'Brad Pitt'; // 세터 console.log(person.fullName); // Brad Pitt person 객체의 fullName 프로퍼티의 서술자 설정 중, “enumerable: false”로 설정했으므로 “console.log(person);” 코드로는 fullName 프로퍼티가 포함되지 않습니다.
  • 21. 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.