[번역] Private Members in JavaScript -Douglas Crockford linguistics

http://javascript.crockford.com/private.html

JavaScript 는 세상에서 가장 오해받는 언어이다. 일부에선, private (속성의;역자) instance 변수와 메소드의 부재로 인해, 객체의 '정보 은닉' 기능이 결여되어 있다고 믿기도 한다. 그러나 이것은 오해다. JavaScript 객체는 private 멤버를 가질 수 있다. 여기 해답이 있다.


Objects


JavaScript 는 근본적으로 거의 object 이다. Array type도 object 이고, Function type도 object 이며, Object type도 object 이다. 그럼 여기서 말하는 object 란 무엇인가? object 는 name-value 쌍의 집합이다. name 은 string 이고, value 는 string, number, boolean, 그리고 (array 와 function 을 포함한) object 이다. 마치 hashtable 처럼 구현되기 때문에 아주 빠르게 value 에 접근할 수 있다.

만약 value 가 function 이라면, 이것을 method 라고 볼 수 있다. object 의 한 메소드가 호출되면, 'this' 변수는 해당 object 가 되고, 이 메소드는 'this' 변수를 통해 instance 변수에 접근하게 된다.

object 는 '생성자'라는 함수에 의해 생성된다. 이 함수는 object 를 초기화한다. 이 '생성자'에서, 여타의 언어에서 제공되는 class 의 속성들-static 변수와 메소드를 포함한- 이 제공된다.


Public


object 의 멤버는 모두 public 멤버이다. 어떤 function 이든 이 멤버에 접근해서 수정하거나 지우거나 또는 새로운 멤버를 추가할 수 있다. 여기, 새로운 object 에 멤버를 추가하는 2가지 대표적인 방법이 있다.

In the constructor

이 기법은 보통 public (속성의;역자) instance 변수를 초기화하는데 사용된다. '생성자'에서 사용된 'this' 변수는 새로운 멤버를 추가하는데 사용된다.

function Container(param) {
    this.member = param;
}

다음과 같이 새로운 object 를 생성하면,

var myContainer = new Container('abc');
myContainer.member 는 'abc'라는 값을 갖는다.

In the prototype

이 기법은 보통 public 메소드를 추가하는데 사용된다. 사용된 멤버 변수가 객체내에 이미 존재하던 것이 아니면, 객체의 생성자의 prototype 멤버로부터 찾아오게 된다. 이 prototype 메커니즘은 상속 구현에 사용되며 또한, prototype 을 사용하면 메모리 사용도 줄일 수 있다. 하나의 '생성자'로부터 생성된 모든 object 에 하나의 메소드를 추가하고자 한다면, 그 function 을 '생성자'의 prototype 에 추가하면 된다.

Container.prototype.stamp = function(string) {
return this.member + string; 
};

이제 다음과 같이 해당 메소드를 호출할 수 있게 되었고,

myContainer.stamp('def');
이는 결과적으로 'abcdef' 라는 값을 산출한다.


Private


private 멤버는 생성자에서 만들 수 있다. 일반적으로 var 로 선언한 변수와 함수의 매개변수는 private 멤버이다.

function Container(param) {
    this.member = param;
    var secret = 3;
    var that = this;
}


이 생성자는 param, secret, that 이라는 3개의 private instance 변수를 생성한다. object의 멤버로 생성되었지만, 이 변수들은 외부에서도, public 메소드에서도 접근할 수 없다. 이것들은 private 메소드에서 접근 가능한데, private 메소드는 생성자 내부에서의 function 정의로 구현된다.

function Container(param) {
    function dec() {
        if (secret > 0) {
            secret += -1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;
}


private 메소드인 dec 는 instance 변수인 secret 을 검사해서, 0 보다 크면, 1 감소시키고 true 를 리턴한다. 그렇지 않다면, false 를 리턴한다. 이로인해 이 object 의 사용을  3회로 제한할 수 있게 되었다.

규정대로라면, 우리는 private 속성의 that 변수를 만들어서, object 가 private 메소드에서 가용하게 할 수 있는데, 이는 ECMAScript 스펙에 의해 inner fuction 에서 this 가 잘못 세팅되는 경우에 대한 차선책이다.

private 메소드는 public 메소드에서 호출될 수 없다. 보다 쓸만한 private 메소드 구현을 위해 이제 privileged 메소드를 알아봐야겠다.


Privileged


privileged 메소드는 private 변수와 메소드에 접근할 수 있으며, 또한, public 메소드와 외부에서 이 메소드를 사용할 수 있다. privileged 메소드를 삭제하거나 대체할 수 있는 반면, 수정하거나 secret 을 공개하게 할 수는 없다.

function Container(param) {
    function dec() {
        if (secret > 0) {
            secret += -1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;

    this.service = function() {
        if (dec()) {
            return that.member;
        } else {
            return null;
        }
    };
}


service 는 privileged 메소드이다. myContainer.service()를 호출하면 처음 3번은 'abc'를 리턴하고, 그후에는 null 을 리턴한다. service 는 private 인 dec 메소드를 호출하고 dec 는 private 변수인 secret 에 접근한다. service 는 타 object 와 메소드에서 사용할 수 있지만, private 멤버에의 직접적인 접근은 허용하지 않는다.


Closures


JavaScript 에서 이러한 public, private, privileged 멤버들의 구현이 가능한 것은, closure 때문이다. closure 의 의미는(Javascript의 closure 구현이 시사하는 바는), inner function 은 outer function 의 var 선언 변수와 매개변수에 접근할 수 있으며, 심지어 outer function 이 리턴된 이후에도 가능하다는 뜻이다. 이는 굉장히 강력한 언어 속성인데, JavaScript 에서 어떻게 이것이 가능한지 파헤쳐놓은 책은 아직은 없다. 대부분 아예 언급할 생각조차 없는 것 같다.

private 과 privileged 멤버는 object 가 생성될 때에만 만들 수 있다. 반면, public 멤버는 언제든 만들 수 있다.


Patterns


Public

function Constructor(...) {
    this.membername = value;
}
Constructor.prototype.membername = value;


Private

function Constructor(...) {
    var that = this;
    var membername = value;

    function membername(...) {...}
}


Note: function 구문

function membername(...) {...}



var membername = function(...) {...};
표현의 축약이다.


Privileged

function Constructor(...) {
    this.membername = function (...) {...};
}


(원문에) Copyright 2001 Douglas Crockford. All Rights Reserved Wrrrldwide.

핑백

덧글

  • cia_lis 2015/11/06 05:57 # 삭제 답글

    I am really enjoying the themedesign of your blog. Do you ever run into any browser compatibility problems? A handful of my blog readers have complained about my website not operating correctly in Explorer but looks great in Chrome. Do you have any advice to help fix this issue?
  • for 2015/11/07 11:26 # 삭제 답글

    Hello There. I found your blog using msn. This is a really well written article. Ill make sure to bookmark it and return to read more of your useful information. Thanks for the post. I will definitely return.
  • order_cia_lis 2015/11/08 11:24 # 삭제 답글

    Really appreciate you sharing this post.Thanks Again. Really Great.
  • cheap_cia_lis 2015/11/08 11:24 # 삭제 답글

    Really appreciate you sharing this post.Thanks Again. Really Great.
  • via_gra_sale 2015/11/08 11:24 # 삭제 답글

    Really appreciate you sharing this post.Thanks Again. Really Great.
  • via_gra 2015/11/08 11:25 # 삭제 답글

    Really appreciate you sharing this post.Thanks Again. Really Great.
  • cia_lis 2015/11/09 23:27 # 삭제 답글

    Inspiring story, where did you quote it from?
  • via_gra 2015/11/09 23:28 # 삭제 답글

    Inspiring story, where did you quote it from?
  • via_gra 2015/11/09 23:30 # 삭제 답글

    Inspiring story, where did you quote it from?
  • cia_lis 2015/11/09 23:31 # 삭제 답글

    Inspiring story, where did you quote it from?
  • online 2015/11/11 21:41 # 삭제 답글

    Very efficiently written post. It will be valuable to anyone who usess it, as well as myself. Keep doing what you are doing i will definitely read more posts.
  • online 2015/11/18 10:53 # 삭제 답글

    tretinoin chemotherapy
  • online 2015/11/18 10:53 # 삭제 답글

    tretinoin chemotherapy
  • buy_cia_lis 2015/11/24 08:41 # 삭제 답글

    plus offering extras which can announce this kind of the main benefit of the skepticism.
  • buy_via_gra 2015/11/24 08:41 # 삭제 답글

    plus offering extras which can announce this kind of the main benefit of the skepticism.
  • super 2015/11/24 08:41 # 삭제 답글

    plus offering extras which can announce this kind of the main benefit of the skepticism.
  • purchase_sildenafil 2015/11/24 08:41 # 삭제 답글

    plus offering extras which can announce this kind of the main benefit of the skepticism.
  • fast 2015/11/24 08:42 # 삭제 답글

    plus offering extras which can announce this kind of the main benefit of the skepticism.
  • buy_cia_lis 2015/12/17 12:02 # 삭제 답글

    This is one awesome blog post. Keep writing.
  • buy_via_gra 2015/12/17 12:03 # 삭제 답글

    This is one awesome blog post. Keep writing.
  • cia_lis 2015/12/17 12:03 # 삭제 답글

    This is one awesome blog post. Keep writing.
  • via_gra 2015/12/17 12:03 # 삭제 답글

    This is one awesome blog post. Keep writing.
  • pills 2015/12/19 09:51 # 삭제 답글

    This is why Facebook games are becoming more popular. The ease of use and dissemination of content, tagging
  • via_gra 2015/12/19 09:52 # 삭제 답글

    This is why Facebook games are becoming more popular. The ease of use and dissemination of content, tagging
  • order_via_gra 2015/12/19 09:52 # 삭제 답글

    This is why Facebook games are becoming more popular. The ease of use and dissemination of content, tagging
  • via_gra 2015/12/19 09:52 # 삭제 답글

    This is why Facebook games are becoming more popular. The ease of use and dissemination of content, tagging
  • cheap 2015/12/23 02:06 # 삭제 답글

    Great, thanks for sharing this blog.Really thank you!
  • cia_lis 2015/12/23 02:06 # 삭제 답글

    Great, thanks for sharing this blog.Really thank you!
  • cia_lis 2015/12/23 02:07 # 삭제 답글

    Great, thanks for sharing this blog.Really thank you!
  • cia_lis 2015/12/23 02:07 # 삭제 답글

    Great, thanks for sharing this blog.Really thank you!
  • cia_lis 2015/12/23 02:07 # 삭제 답글

    Great, thanks for sharing this blog.Really thank you!
  • generic_cia_lis 2015/12/23 20:31 # 삭제 답글

    We're a group of volunteers and starting a new scheme in our community.
  • online 2016/01/20 22:16 # 삭제 답글

    I'm seeking weblogs which all have fantastic guidance on what's popular and specifically what the top rated makeup is..
  • suppliers 2016/01/20 22:16 # 삭제 답글

    I'm seeking weblogs which all have fantastic guidance on what's popular and specifically what the top rated makeup is..
  • online 2016/01/20 22:17 # 삭제 답글

    I'm seeking weblogs which all have fantastic guidance on what's popular and specifically what the top rated makeup is..
  • suppliers 2016/01/20 22:17 # 삭제 답글

    I'm seeking weblogs which all have fantastic guidance on what's popular and specifically what the top rated makeup is..
  • cia_lis 2016/01/23 02:41 # 삭제 답글

    I have read several good stuff here. Certainly worth bookmarking for revisiting. I surprise how much effort you put to make such a magnificent informative web site.
  • fast 2016/01/23 02:42 # 삭제 답글

    I have read several good stuff here. Certainly worth bookmarking for revisiting. I surprise how much effort you put to make such a magnificent informative web site.
  • for 2016/01/23 02:42 # 삭제 답글

    I have read several good stuff here. Certainly worth bookmarking for revisiting. I surprise how much effort you put to make such a magnificent informative web site.
  • fast 2016/01/23 02:42 # 삭제 답글

    I have read several good stuff here. Certainly worth bookmarking for revisiting. I surprise how much effort you put to make such a magnificent informative web site.
  • for 2016/01/23 02:43 # 삭제 답글

    I have read several good stuff here. Certainly worth bookmarking for revisiting. I surprise how much effort you put to make such a magnificent informative web site.
  • generic 2016/02/03 03:20 # 삭제 답글

    How significantly of an special post, keep on posting much better half
  • fast 2016/02/04 06:15 # 삭제 답글

    As soon as I found this internet site I went on reddit to share some of the love with them.
  • fast 2016/02/04 06:15 # 삭제 답글

    As soon as I found this internet site I went on reddit to share some of the love with them.
  • purchase_cia_lis 2016/02/04 06:16 # 삭제 답글

    As soon as I found this internet site I went on reddit to share some of the love with them.
  • purchase_via_gra 2016/02/04 06:16 # 삭제 답글

    As soon as I found this internet site I went on reddit to share some of the love with them.
  • side 2016/02/12 20:34 # 삭제 답글

    What's up it's me, I am also visiting this site daily, this website is actually pleasant and the visitors are really sharing fastidious thoughts.
  • side 2016/02/12 20:34 # 삭제 답글

    What's up it's me, I am also visiting this site daily, this website is actually pleasant and the visitors are really sharing fastidious thoughts.
  • cia_lis_online 2016/02/12 20:35 # 삭제 답글

    What's up it's me, I am also visiting this site daily, this website is actually pleasant and the visitors are really sharing fastidious thoughts.
  • via_gra_online 2016/02/12 20:35 # 삭제 답글

    What's up it's me, I am also visiting this site daily, this website is actually pleasant and the visitors are really sharing fastidious thoughts.
  • without 2016/03/30 03:49 # 삭제 답글

    If you are going for best contents like myself, simply go to see this site all
  • via_gra 2016/03/30 03:49 # 삭제 답글

    If you are going for best contents like myself, simply go to see this site all
  • cia_lis 2016/03/30 03:49 # 삭제 답글

    If you are going for best contents like myself, simply go to see this site all
  • fast 2016/03/30 03:50 # 삭제 답글

    If you are going for best contents like myself, simply go to see this site all
  • of 2016/04/05 20:27 # 삭제 답글

    My brother recommended I might like this website. He was totally right. This post truly made my day. You cann't imagine simply how much time I had spent for this info! Thanks!
  • of 2016/04/05 20:27 # 삭제 답글

    My brother recommended I might like this website. He was totally right. This post truly made my day. You cann't imagine simply how much time I had spent for this info! Thanks!
  • order_cia_lis 2016/04/05 20:28 # 삭제 답글

    My brother recommended I might like this website. He was totally right. This post truly made my day. You cann't imagine simply how much time I had spent for this info! Thanks!
  • order_via_gra 2016/04/05 20:28 # 삭제 답글

    My brother recommended I might like this website. He was totally right. This post truly made my day. You cann't imagine simply how much time I had spent for this info! Thanks!
  • dosage 2016/04/06 00:43 # 삭제 답글

    I have learn some good stuff here. Certainly price bookmarking for revisiting.
  • without 2016/04/06 00:44 # 삭제 답글

    I have learn some good stuff here. Certainly price bookmarking for revisiting.
  • dosage 2016/04/06 00:44 # 삭제 답글

    I have learn some good stuff here. Certainly price bookmarking for revisiting.
  • without 2016/04/06 00:44 # 삭제 답글

    I have learn some good stuff here. Certainly price bookmarking for revisiting.
  • generic_cia_lis 2016/04/06 04:01 # 삭제 답글

    Thank you for every other informative blog. The place else may just I get that type of info written in such a perfect means? I've a project that I'm just now working on, and I have been at the glance out for such information.
  • via_gra_dosage 2016/04/06 04:02 # 삭제 답글

    Thank you for every other informative blog. The place else may just I get that type of info written in such a perfect means? I've a project that I'm just now working on, and I have been at the glance out for such information.
  • cia_lis_order 2016/04/06 04:02 # 삭제 답글

    Thank you for every other informative blog. The place else may just I get that type of info written in such a perfect means? I've a project that I'm just now working on, and I have been at the glance out for such information.
  • via_gra_order 2016/04/06 04:02 # 삭제 답글

    Thank you for every other informative blog. The place else may just I get that type of info written in such a perfect means? I've a project that I'm just now working on, and I have been at the glance out for such information.
  • cia_lis 2016/04/06 18:45 # 삭제 답글

    Merely a smiling visitor here to share the adore , btw outstanding style. Audacity, more audacity and always audacity. by Georges Jacques Danton.
  • of 2016/04/06 18:45 # 삭제 답글

    Merely a smiling visitor here to share the adore , btw outstanding style. Audacity, more audacity and always audacity. by Georges Jacques Danton.
  • order_cia_lis 2016/04/06 18:49 # 삭제 답글

    Merely a smiling visitor here to share the adore , btw outstanding style. Audacity, more audacity and always audacity. by Georges Jacques Danton.
  • order_via_gra 2016/04/06 18:50 # 삭제 답글

    Merely a smiling visitor here to share the adore , btw outstanding style. Audacity, more audacity and always audacity. by Georges Jacques Danton.
  • cia_lis 2016/04/07 09:21 # 삭제 답글

    I really like your writing style, fantastic information, thanks for putting up
  • via_gra_dosage 2016/04/07 09:24 # 삭제 답글

    I really like your writing style, fantastic information, thanks for putting up
  • selbstkleb 2016/04/10 21:45 # 삭제 답글

    This is a fantastic website and I can not recommend you guys enough. I really appreciate your post. It is very helpful for all the people on the web.
    <a href="http://selbstklebendebh.de/">selbstklebende bh</a>
  • generic 2016/04/14 04:01 # 삭제 답글

    Enjoyed examining this, very good stuff, thankyou . While thou livest keep a good tongue in thy head. by William Shakespeare.
  • cia_lis 2016/04/14 04:02 # 삭제 답글

    Enjoyed examining this, very good stuff, thankyou . While thou livest keep a good tongue in thy head. by William Shakespeare.
  • via_gra 2016/04/14 04:02 # 삭제 답글

    Enjoyed examining this, very good stuff, thankyou . While thou livest keep a good tongue in thy head. by William Shakespeare.
  • online 2016/04/15 09:27 # 삭제 답글

    reverse phone lookup cell free I wish to voice my gratitude for your generosity giving support to individuals
  • discount 2016/04/15 09:28 # 삭제 답글

    reverse phone lookup cell free I wish to voice my gratitude for your generosity giving support to individuals
  • online 2016/04/15 09:28 # 삭제 답글

    reverse phone lookup cell free I wish to voice my gratitude for your generosity giving support to individuals
  • discount 2016/04/15 09:28 # 삭제 답글

    reverse phone lookup cell free I wish to voice my gratitude for your generosity giving support to individuals
  • cia_lis_price 2016/04/16 19:10 # 삭제 답글

    I'm trying to find sites that have already fantastic useful information on what's popular and what is the optimum makeup products is..
  • via_gra_price 2016/04/16 19:10 # 삭제 답글

    I'm trying to find sites that have already fantastic useful information on what's popular and what is the optimum makeup products is..
  • discount_cia_lis 2016/04/16 19:11 # 삭제 답글

    I'm trying to find sites that have already fantastic useful information on what's popular and what is the optimum makeup products is..
  • discount_via_gra 2016/04/16 19:11 # 삭제 답글

    I'm trying to find sites that have already fantastic useful information on what's popular and what is the optimum makeup products is..
  • cia_lis 2016/04/20 21:02 # 삭제 답글

    Woah! I'm really loving the templatetheme of this website. It's simple, yet effective. A lot of times it's hard to get that perfect balance between usability and visual appeal. I must say you have done a great job with this. In addition, the blog loads super quick for me on Firefox. Excellent Blog!
  • buy_via_gra 2016/04/20 21:02 # 삭제 답글

    Woah! I'm really loving the templatetheme of this website. It's simple, yet effective. A lot of times it's hard to get that perfect balance between usability and visual appeal. I must say you have done a great job with this. In addition, the blog loads super quick for me on Firefox. Excellent Blog!
  • cia_lis_india 2016/04/20 21:03 # 삭제 답글

    Woah! I'm really loving the templatetheme of this website. It's simple, yet effective. A lot of times it's hard to get that perfect balance between usability and visual appeal. I must say you have done a great job with this. In addition, the blog loads super quick for me on Firefox. Excellent Blog!
  • indian_via_gra 2016/04/20 21:03 # 삭제 답글

    Woah! I'm really loving the templatetheme of this website. It's simple, yet effective. A lot of times it's hard to get that perfect balance between usability and visual appeal. I must say you have done a great job with this. In addition, the blog loads super quick for me on Firefox. Excellent Blog!
  • cheap_cia_lis 2016/04/22 05:52 # 삭제 답글

    Wonderful beat ! I wish to apprentice while you amend your web site, how can i subscribe for a blog site? The account aided me a acceptable deal. I had been tiny bit acquainted of this your broadcast offered bright clear idea
  • via_gra 2016/04/27 09:52 # 삭제 답글

    Really appreciate you sharing this post.Thanks Again. Really Great.
  • cia_lis 2016/04/27 09:52 # 삭제 답글

    Really appreciate you sharing this post.Thanks Again. Really Great.
  • generic 2016/04/27 09:52 # 삭제 답글

    Really appreciate you sharing this post.Thanks Again. Really Great.
  • generic 2016/04/27 09:53 # 삭제 답글

    Really appreciate you sharing this post.Thanks Again. Really Great.
  • generic 2016/04/28 10:45 # 삭제 답글

    Enjoyed examining this, very good stuff, thankyou. Talk sense to a fool and he calls you foolish. by Euripides.
  • herbal 2016/04/28 10:47 # 삭제 답글

    Enjoyed examining this, very good stuff, thankyou. Talk sense to a fool and he calls you foolish. by Euripides.
  • price_via_gra 2016/04/28 23:50 # 삭제 답글

    Maintain the excellent job mate. This web blog publish shows how well you comprehend and know this subject.
  • via_gra 2016/04/28 23:51 # 삭제 답글

    Maintain the excellent job mate. This web blog publish shows how well you comprehend and know this subject.
  • cia_lis 2016/04/28 23:52 # 삭제 답글

    Maintain the excellent job mate. This web blog publish shows how well you comprehend and know this subject.
  • cia_lis 2016/04/28 23:52 # 삭제 답글

    Maintain the excellent job mate. This web blog publish shows how well you comprehend and know this subject.
  • pills 2016/04/28 23:53 # 삭제 답글

    Maintain the excellent job mate. This web blog publish shows how well you comprehend and know this subject.
댓글 입력 영역
◀ 다음덧글    이전덧글 ▶