[번역] 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.

핑백

덧글

  • payday_loans 2015/09/05 16:26 # 삭제 답글

    I am not sure where you are getting your info, but great topic. I needs to spend some time learning much more or understanding more. Thanks for fantastic information I was looking for this info for my mission.
  • payday_loans 2015/09/06 04:18 # 삭제 답글

    I'm seeking weblogs which all have fantastic guidance on what's popular and specifically what the top rated makeup is..
  • payday_loans 2015/09/06 04:19 # 삭제 답글

    I'm seeking weblogs which all have fantastic guidance on what's popular and specifically what the top rated makeup is..
  • payday_loans 2015/09/06 04:19 # 삭제 답글

    I'm seeking weblogs which all have fantastic guidance on what's popular and specifically what the top rated makeup is..
  • payday_loans 2015/09/06 04:20 # 삭제 답글

    I'm seeking weblogs which all have fantastic guidance on what's popular and specifically what the top rated makeup is..
  • cash 2015/09/06 10:36 # 삭제 답글

    Fckin amazing things here. Im very glad to see your post. Thanks a lot and i'm looking forward to contact you. Will you kindly drop me a mail?
  • payday_loans 2015/09/06 15:24 # 삭제 답글

    tretinoin chemotherapy
  • payday_loans 2015/09/06 15:26 # 삭제 답글

    tretinoin chemotherapy
  • payday_advances 2015/09/10 15:56 # 삭제 답글

    Do you have a spam problem on this site I also am
  • cash 2015/09/10 15:57 # 삭제 답글

    Do you have a spam problem on this site I also am
  • fax 2015/09/10 15:57 # 삭제 답글

    Do you have a spam problem on this site I also am
  • payday 2015/09/10 15:57 # 삭제 답글

    Do you have a spam problem on this site I also am
  • payday_loans 2015/09/10 17:17 # 삭제 답글

    Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You obviously know what youre talking about, why throw away your intelligence on just posting videos to your site when you could be giving us something enlightening to read?
  • payday_loans 2015/09/10 17:18 # 삭제 답글

    Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You obviously know what youre talking about, why throw away your intelligence on just posting videos to your site when you could be giving us something enlightening to read?
  • payday_loans 2015/09/10 17:18 # 삭제 답글

    Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You obviously know what youre talking about, why throw away your intelligence on just posting videos to your site when you could be giving us something enlightening to read?
  • payday_loans 2015/09/10 17:19 # 삭제 답글

    Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You obviously know what youre talking about, why throw away your intelligence on just posting videos to your site when you could be giving us something enlightening to read?
  • cia_lis 2015/09/21 20:28 # 삭제 답글

    I truly appreciate this post. I've been looking everywhere for this! Thank goodness I found it on Bing. You've made my day! Thank you again!
  • via_gra 2015/09/21 20:28 # 삭제 답글

    I truly appreciate this post. I've been looking everywhere for this! Thank goodness I found it on Bing. You've made my day! Thank you again!
  • cia_lis 2015/09/21 20:28 # 삭제 답글

    I truly appreciate this post. I've been looking everywhere for this! Thank goodness I found it on Bing. You've made my day! Thank you again!
  • via_gra 2015/09/21 20:29 # 삭제 답글

    I truly appreciate this post. I've been looking everywhere for this! Thank goodness I found it on Bing. You've made my day! Thank you again!
  • online 2015/09/22 00:59 # 삭제 답글

    Wow, superb blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is wonderful, let alone the content!
  • online 2015/09/22 01:00 # 삭제 답글

    Wow, superb blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is wonderful, let alone the content!
  • online 2015/09/22 01:00 # 삭제 답글

    Wow, superb blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is wonderful, let alone the content!
  • online 2015/09/22 01:02 # 삭제 답글

    Wow, superb blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is wonderful, let alone the content!
  • cia_lis 2015/09/23 16:09 # 삭제 답글

    Im not that much of a online reader to be honest but your blogs really nice, keep it up! I'll go ahead and bookmark your site to come back later. Cheers
  • via_gra_pills 2015/09/23 16:10 # 삭제 답글

    Im not that much of a online reader to be honest but your blogs really nice, keep it up! I'll go ahead and bookmark your site to come back later. Cheers
  • cia_lis_samples 2015/09/24 01:26 # 삭제 답글

    You have brought up a very excellent details , regards for the post.
  • via_gra_pills 2015/09/24 01:26 # 삭제 답글

    You have brought up a very excellent details , regards for the post.
  • cia_lis 2015/09/24 08:44 # 삭제 답글

    I think this is one of the most significant information for me. And i'm glad reading your article. But should remark on some general things, The web site style is wonderful, the articles is really excellent D. Good job, cheers
  • via_gra_pills 2015/09/24 08:45 # 삭제 답글

    I think this is one of the most significant information for me. And i'm glad reading your article. But should remark on some general things, The web site style is wonderful, the articles is really excellent D. Good job, cheers
  • buy_cia_lis 2015/09/26 09:59 # 삭제 답글

    Hi there! This is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us beneficial information to work on. You have done a marvellous job!
  • buy_via_gra 2015/09/26 09:59 # 삭제 답글

    Hi there! This is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us beneficial information to work on. You have done a marvellous job!
  • payday_loans 2015/10/13 12:01 # 삭제 답글

    Great, thanks for sharing this blog.Really thank you!
  • payday_loans 2015/10/13 12:01 # 삭제 답글

    Great, thanks for sharing this blog.Really thank you!
  • payday_loans 2015/10/13 12:02 # 삭제 답글

    Great, thanks for sharing this blog.Really thank you!
  • payday_loans 2015/10/13 12:02 # 삭제 답글

    Great, thanks for sharing this blog.Really thank you!
  • online_cia_lis 2015/10/17 05:30 # 삭제 답글

    I have learn some good stuff here. Certainly price bookmarking for revisiting.
  • generic_cia_lis 2015/10/17 05:33 # 삭제 답글

    I have learn some good stuff here. Certainly price bookmarking for revisiting.
  • safe 2015/10/17 21:39 # 삭제 답글

    very nice submit, i definitely love this website, keep on it
  • loans 2015/10/17 21:44 # 삭제 답글

    very nice submit, i definitely love this website, keep on it
  • canadian_cia_lis 2015/10/22 03:14 # 삭제 답글

    what are some really good and popular websites for blogging? ?? .
  • canadian_via_gra 2015/10/22 03:14 # 삭제 답글

    what are some really good and popular websites for blogging? ?? .
  • no 2015/10/30 17:00 # 삭제 답글

    I really like your writing style, fantastic information, thanks for putting up
  • for 2015/10/30 17:04 # 삭제 답글

    I really like your writing style, fantastic information, thanks for putting up
  • online 2015/11/05 01:40 # 삭제 답글

    Great blog! I am loving it!! Will come back again. I am taking your feeds also
  • without 2015/11/05 01:40 # 삭제 답글

    Great blog! I am loving it!! Will come back again. I am taking your feeds also
  • cia_lis 2015/11/06 05:54 # 삭제 답글

    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?
  • via_gra 2015/11/06 05:54 # 삭제 답글

    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?
  • cia_lis 2015/11/06 05:55 # 삭제 답글

    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?
  • online_cia_lis 2015/11/06 05:56 # 삭제 답글

    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?
  • 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.
댓글 입력 영역
◀ 다음덧글    이전덧글 ▶