Skip to content

Instantly share code, notes, and snippets.

@uyu423
Last active April 24, 2017 10:29
Show Gist options
  • Save uyu423/fa27377b768f3d9c78ed3256f2efdc6b to your computer and use it in GitHub Desktop.
Save uyu423/fa27377b768f3d9c78ed3256f2efdc6b to your computer and use it in GitHub Desktop.
class Money {
constructor(value) {
if (value < 0) throw Error('Money Type Valiation Exception');
this.value = value;
}
}
class Email {
constructor(email) {
const regExp = /^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*\.[a-zA-Z]{2,3}$/i;
if (!regExp.test(email)) throw Error('Email Type Validation Exception')
this.email = email;
Object.defineProperty(this, 'username', {
value: email.split('@')[0],
enumerable: false,
});
Object.defineProperty(this, 'domain', {
value: email.split('@')[1],
enumerable: false,
});
}
}
class User {
constructor(object) {
this.name = object.name;
this.credit = new Money(object.credit);
this.email = new Email(object.email);
}
}
const yowu = new User({
name: 'Yowu',
credit: 10000,
email: 'yowu@plating.co.kr',
});
console.log(yowu);
// Real Output
// User {
// name: 'Yowu',
// credit: Money { value: 10000 },
// email: Email { email: 'yowu@plating.co.kr' } }
// 아래와 같이 출력되게 하는 방법이 있을까..
// User {
// name: 'Yowu',
// credit: 10000,
// email: 'yowu@plating.co.kr' }
@uyu423
Copy link
Author

uyu423 commented Apr 24, 2017

해결책 1. 별로 마음에는 안든다..

class User {
  constructor(object) {
    this.name = object.name;
    this.credit = new Money(object.credit);
    this.email = new Email(object.email);
  }
  toString() {
    return {
      name: this.name,
      credit: this.credit.value,
      email: this.email.email,
    }
  }
}

console.log(yowu.toString());
// { name: 'Yowu', credit: 10000, email: 'yowu@plating.co.kr' }

@ungikim
Copy link

ungikim commented Apr 24, 2017

Javascript 는 모르겠는데 Java 의 개발환경에서는 보통 Client 에 보여지는 부분이 JSON 인 경우 JSON Serialize 할 때 저런 처리를 함...

@uyu423
Copy link
Author

uyu423 commented Apr 24, 2017

David Seunghoon Ko 님이 제시해주신 코드 (https://www.facebook.com/groups/codingeverybody/permalink/1642888369085026/)
image

@uyu423
Copy link
Author

uyu423 commented Apr 24, 2017

@ungikim 사실 저렇게 해도 문제는 없는데 분명 더 아름답고 알아서 해주는 방법이 있을거 같아서리..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment