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

핑백

덧글

  • Smithe42 2014/11/30 12:43 # 삭제 답글

    Because here is a list of multiplayer games is that the leave was asked dfkcbdbkffeedcga
  • purchase_cia_lis 2014/12/14 08:27 # 삭제 답글

    Wow, this article is fastidious, my younger sister is analyzing these kinds of things, thus I am going to convey her.
  • sale 2014/12/14 08:30 # 삭제 답글

    Wow, this article is fastidious, my younger sister is analyzing these kinds of things, thus I am going to convey her.
  • 2014/12/18 10:19 # 삭제 답글

    좋은 쓰기까지, 나는 자신의 블로그를 정기적으로 방문자 오전, 우수한 운영까지 유지하고, 그것은 긴 시간 동안 정기적 인 방문자가 될 것입니다.
  • cialis 2015/04/10 01:42 # 삭제 답글

    Farmville farms even include free gift that
  • cialis 2015/04/10 01:43 # 삭제 답글

    Farmville farms even include free gift that
  • viagra 2015/04/10 01:43 # 삭제 답글

    Farmville farms even include free gift that
  • viagra 2015/04/10 01:43 # 삭제 답글

    Farmville farms even include free gift that
  • cialis 2015/04/10 01:44 # 삭제 답글

    Farmville farms even include free gift that
  • cialis 2015/04/10 20:22 # 삭제 답글

    Howdy! Would you mind if I share your blog with my twitter group? Theres lots of people that I believe would really enjoy your content. Please let me know. Thanks
  • cheap_cialis 2015/04/10 20:23 # 삭제 답글

    Howdy! Would you mind if I share your blog with my twitter group? Theres lots of people that I believe would really enjoy your content. Please let me know. Thanks
  • viagra_pills 2015/04/10 20:23 # 삭제 답글

    Howdy! Would you mind if I share your blog with my twitter group? Theres lots of people that I believe would really enjoy your content. Please let me know. Thanks
  • canadian_viagra 2015/04/10 20:23 # 삭제 답글

    Howdy! Would you mind if I share your blog with my twitter group? Theres lots of people that I believe would really enjoy your content. Please let me know. Thanks
  • cialis 2015/04/10 20:24 # 삭제 답글

    Howdy! Would you mind if I share your blog with my twitter group? Theres lots of people that I believe would really enjoy your content. Please let me know. Thanks
  • generic_cialis 2015/04/11 11:46 # 삭제 답글

    I appreciate, cause I found just what I was looking for. You have ended my 4 day long hunt! God Bless you man. Have a great day. Bye
  • generic_viagra 2015/04/11 11:47 # 삭제 답글

    I appreciate, cause I found just what I was looking for. You have ended my 4 day long hunt! God Bless you man. Have a great day. Bye
  • cialis_online 2015/04/11 11:47 # 삭제 답글

    I appreciate, cause I found just what I was looking for. You have ended my 4 day long hunt! God Bless you man. Have a great day. Bye
  • viagra_online 2015/04/11 11:47 # 삭제 답글

    I appreciate, cause I found just what I was looking for. You have ended my 4 day long hunt! God Bless you man. Have a great day. Bye
  • cialis 2015/04/13 04:50 # 삭제 답글

    I'm trying to find sites that have already fantastic useful information on what's popular and what is the optimum makeup products is..
  • viagra 2015/04/13 04:51 # 삭제 답글

    I'm trying to find sites that have already fantastic useful information on what's popular and what is the optimum makeup products is..
  • cialis 2015/04/13 04:51 # 삭제 답글

    I'm trying to find sites that have already fantastic useful information on what's popular and what is the optimum makeup products is..
  • viagra 2015/04/13 04:52 # 삭제 답글

    I'm trying to find sites that have already fantastic useful information on what's popular and what is the optimum makeup products is..
  • cialis 2015/04/13 13:42 # 삭제 답글

    When some one searches for his necessary thing, so heshe desires to be available that in detail, thus that thing is maintained over here.
  • from 2015/04/13 13:43 # 삭제 답글

    When some one searches for his necessary thing, so heshe desires to be available that in detail, thus that thing is maintained over here.
  • cialis 2015/04/13 13:43 # 삭제 답글

    When some one searches for his necessary thing, so heshe desires to be available that in detail, thus that thing is maintained over here.
  • from 2015/04/13 13:43 # 삭제 답글

    When some one searches for his necessary thing, so heshe desires to be available that in detail, thus that thing is maintained over here.
  • cheap_cialis 2015/04/13 14:48 # 삭제 답글

    Today, while I was at work, my sister stole my apple ipad and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My apple ipad is now broken and she has 83 views. I know this is entirely off topic but I had to share it with someone!
  • generic 2015/04/13 14:49 # 삭제 답글

    Today, while I was at work, my sister stole my apple ipad and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My apple ipad is now broken and she has 83 views. I know this is entirely off topic but I had to share it with someone!
  • generic_cialis 2015/04/13 14:49 # 삭제 답글

    Today, while I was at work, my sister stole my apple ipad and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My apple ipad is now broken and she has 83 views. I know this is entirely off topic but I had to share it with someone!
  • viagra_online 2015/04/13 14:50 # 삭제 답글

    Today, while I was at work, my sister stole my apple ipad and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My apple ipad is now broken and she has 83 views. I know this is entirely off topic but I had to share it with someone!
  • viagra 2015/04/14 02:11 # 삭제 답글

    Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how can we communicate?
  • generic 2015/04/14 02:11 # 삭제 답글

    Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how can we communicate?
  • viagra 2015/04/14 02:12 # 삭제 답글

    Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how can we communicate?
  • generic 2015/04/14 02:12 # 삭제 답글

    Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how can we communicate?
  • generic 2015/04/14 02:12 # 삭제 답글

    Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how can we communicate?
  • cialis_sale 2015/04/15 20:39 # 삭제 답글

    Spot lets start off perform on this writeup, I seriously consider this astounding internet site needs much more consideration. Ill apt to become once again to find out to read considerably a lot more, thank you that information.
  • generic_viagra 2015/04/15 20:39 # 삭제 답글

    Spot lets start off perform on this writeup, I seriously consider this astounding internet site needs much more consideration. Ill apt to become once again to find out to read considerably a lot more, thank you that information.
  • cialis_online 2015/04/16 02:25 # 삭제 답글

    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. All the best
  • viagra 2015/04/16 02:25 # 삭제 답글

    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. All the best
  • tadalafil 2015/04/16 02:25 # 삭제 답글

    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. All the best
  • cialis 2015/04/16 02:26 # 삭제 답글

    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. All the best
  • buy_cialis 2015/04/16 02:26 # 삭제 답글

    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. All the best
  • cialis_pills 2015/04/19 03:04 # 삭제 답글

    I truly appreciate this article.Really thank you! Fantastic.
  • fast 2015/04/19 03:04 # 삭제 답글

    I truly appreciate this article.Really thank you! Fantastic.
  • cialis 2015/04/20 09:17 # 삭제 답글

    Today, while I was at work, my sister stole my apple ipad and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My apple ipad is now broken and she has 83 views. I know this is entirely off topic but I had to share it with someone!
  • cialis 2015/04/21 08:07 # 삭제 답글

    I truly prize your function, Wonderful post.
  • viagra 2015/04/21 08:07 # 삭제 답글

    I truly prize your function, Wonderful post.
  • cialis 2015/04/21 08:07 # 삭제 답글

    I truly prize your function, Wonderful post.
  • cialis 2015/04/21 08:08 # 삭제 답글

    I truly prize your function, Wonderful post.
  • viagra_sale 2015/04/23 13:48 # 삭제 답글

    reverse phone lookup free results I am no longer positive
  • cheap_viagra 2015/04/23 13:48 # 삭제 답글

    reverse phone lookup free results I am no longer positive
  • cialis 2015/04/23 13:48 # 삭제 답글

    reverse phone lookup free results I am no longer positive
  • generic_viagra 2015/04/23 13:49 # 삭제 답글

    reverse phone lookup free results I am no longer positive
  • tadalafil 2015/04/23 23:00 # 삭제 답글

    While think this kind of Real estate property industry hope against hope turn back in the positive course? Or maybe can it be at a standstill very young to tell? We're glimpse many terracing property foreclosures modish
  • sildenafil 2015/04/23 23:01 # 삭제 답글

    While think this kind of Real estate property industry hope against hope turn back in the positive course? Or maybe can it be at a standstill very young to tell? We're glimpse many terracing property foreclosures modish
  • cialis 2015/04/25 01:00 # 삭제 답글

    Ovver the course of the initial period, they began tto form grooup
  • cheap_cialis 2015/04/25 01:00 # 삭제 답글

    Ovver the course of the initial period, they began tto form grooup
  • cialis 2015/04/25 18:50 # 삭제 답글

    Hello to all, how is everything, I think every one is getting more from this website, and your views are fastidious in support of new viewers.
  • for 2015/04/25 18:50 # 삭제 답글

    Hello to all, how is everything, I think every one is getting more from this website, and your views are fastidious in support of new viewers.
  • cialis 2015/04/27 14:57 # 삭제 답글

    Your goal is to breed all the different dragons
  • viagra 2015/04/27 14:59 # 삭제 답글

    Your goal is to breed all the different dragons
  • discount_viagra 2015/04/28 14:31 # 삭제 답글

    location within my public complexes!
  • cialis_sample 2015/04/28 14:32 # 삭제 답글

    location within my public complexes!
  • cialis 2015/04/29 21:56 # 삭제 답글

    This design is wicked! You obviously know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog well, almostHaHa! Wonderful job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!
  • viagra 2015/04/29 21:56 # 삭제 답글

    This design is wicked! You obviously know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog well, almostHaHa! Wonderful job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!
  • cialis 2015/04/29 21:56 # 삭제 답글

    This design is wicked! You obviously know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog well, almostHaHa! Wonderful job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!
  • pills 2015/04/29 23:51 # 삭제 답글

    whoah this weblog is wonderful i love studying your posts. Stay up the great work! You know, many individuals are searching round for this info, you can aid them greatly.
  • free 2015/04/29 23:51 # 삭제 답글

    whoah this weblog is wonderful i love studying your posts. Stay up the great work! You know, many individuals are searching round for this info, you can aid them greatly.
  • viagra 2015/04/30 16:26 # 삭제 답글

    I'm really enjoying the design and layout of your website. It's a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a designer to create your theme? Excellent work!
  • cialis 2015/04/30 16:28 # 삭제 답글

    I'm really enjoying the design and layout of your website. It's a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a designer to create your theme? Excellent work!
  • viagra 2015/04/30 16:29 # 삭제 답글

    I'm really enjoying the design and layout of your website. It's a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a designer to create your theme? Excellent work!
  • discount_viagra 2015/05/02 01:05 # 삭제 답글

    Wow, awesome blog layout! How long have you been blogging
  • cialis_sample 2015/05/02 01:07 # 삭제 답글

    Wow, awesome blog layout! How long have you been blogging
  • to 2015/05/04 05:40 # 삭제 답글

    Very interesting subject , appreciate it for posting . All human beings should try to learn before they die what they are running from, and to, and why. by James Thurber.
  • dosage 2015/05/04 05:40 # 삭제 답글

    Very interesting subject , appreciate it for posting . All human beings should try to learn before they die what they are running from, and to, and why. by James Thurber.
  • to 2015/05/04 05:40 # 삭제 답글

    Very interesting subject , appreciate it for posting . All human beings should try to learn before they die what they are running from, and to, and why. by James Thurber.
  • to 2015/05/04 05:41 # 삭제 답글

    Very interesting subject , appreciate it for posting . All human beings should try to learn before they die what they are running from, and to, and why. by James Thurber.
  • dosage 2015/05/04 05:41 # 삭제 답글

    Very interesting subject , appreciate it for posting . All human beings should try to learn before they die what they are running from, and to, and why. by James Thurber.
  • viagra 2015/05/04 14:01 # 삭제 답글

    While think this kind of Real estate property industry hope against hope turn back in the positive course? Or maybe can it be at a standstill very young to tell? We're glimpse many terracing property foreclosures modish
  • cialis 2015/05/04 14:03 # 삭제 답글

    While think this kind of Real estate property industry hope against hope turn back in the positive course? Or maybe can it be at a standstill very young to tell? We're glimpse many terracing property foreclosures modish
  • viagra 2015/05/04 14:05 # 삭제 답글

    While think this kind of Real estate property industry hope against hope turn back in the positive course? Or maybe can it be at a standstill very young to tell? We're glimpse many terracing property foreclosures modish
  • viagra 2015/05/04 14:06 # 삭제 답글

    While think this kind of Real estate property industry hope against hope turn back in the positive course? Or maybe can it be at a standstill very young to tell? We're glimpse many terracing property foreclosures modish
  • discount 2015/05/09 03:32 # 삭제 답글

    Id forever want to be update on new articles on this internet site, bookmarked ! .
  • viagra 2015/05/09 03:32 # 삭제 답글

    Id forever want to be update on new articles on this internet site, bookmarked ! .
  • suppliers 2015/05/10 16:51 # 삭제 답글

    Immigration ...the time to read or check out the content or sites we have linked to below the...
  • cialis 2015/05/10 16:53 # 삭제 답글

    Immigration ...the time to read or check out the content or sites we have linked to below the...
  • suppliers 2015/05/10 16:55 # 삭제 답글

    Immigration ...the time to read or check out the content or sites we have linked to below the...
  • cheap_cialis 2015/05/11 20:56 # 삭제 답글

    There is clearly a bundle to realize about this. I suppose you made some good points in features also.
  • viagra_pills 2015/05/12 15:09 # 삭제 답글

    Hello! This is my first comment here so I just wanted to give a quick shout out and tell you I really enjoy
  • buy_cialis 2015/05/12 15:12 # 삭제 답글

    Hello! This is my first comment here so I just wanted to give a quick shout out and tell you I really enjoy
  • viagra_dosage 2015/05/12 19:57 # 삭제 답글

    Wow, marvelous blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is great, as well as the content!
  • cialis_dosage 2015/05/12 19:57 # 삭제 답글

    Wow, marvelous blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is great, as well as the content!
  • cialis_sample 2015/05/12 19:58 # 삭제 답글

    Wow, marvelous blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is great, as well as the content!
  • viagra_sample 2015/05/12 19:58 # 삭제 답글

    Wow, marvelous blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is great, as well as the content!
  • generic 2015/05/14 09:21 # 삭제 답글

    That is some inspirational stuff. Never knew that opinions could be this varied. Be certain to keep writing.
  • herbal_viagra 2015/05/14 09:22 # 삭제 답글

    That is some inspirational stuff. Never knew that opinions could be this varied. Be certain to keep writing.
  • cialis 2015/05/16 10:57 # 삭제 답글

    I needed to thank you for this good read!! I certainly enjoyed every little bit of it. I've got you bookmarked to check out new stuff you post
  • viagra 2015/05/16 10:58 # 삭제 답글

    I needed to thank you for this good read!! I certainly enjoyed every little bit of it. I've got you bookmarked to check out new stuff you post
  • cialis_sale 2015/05/19 20:28 # 삭제 답글

    Hi my friend! I want to say that this post is amazing, great written and include almost all significant infos. I'd like to see more posts like this.
  • viagra_sale 2015/05/19 20:32 # 삭제 답글

    Hi my friend! I want to say that this post is amazing, great written and include almost all significant infos. I'd like to see more posts like this.
댓글 입력 영역
◀ 다음덧글    이전덧글 ▶