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

핑백

덧글

  • 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.
  • online 2016/05/02 18:10 # 삭제 답글

    It is really a nice and helpful piece of info. Im glad that you shared this helpful information with us. Please keep us up to date like this. Thanks for sharing.
  • via_gra_online 2016/05/02 18:10 # 삭제 답글

    It is really a nice and helpful piece of info. Im glad that you shared this helpful information with us. Please keep us up to date like this. Thanks for sharing.
  • without 2016/05/02 18:11 # 삭제 답글

    It is really a nice and helpful piece of info. Im glad that you shared this helpful information with us. Please keep us up to date like this. Thanks for sharing.
  • without 2016/05/02 18:11 # 삭제 답글

    It is really a nice and helpful piece of info. Im glad that you shared this helpful information with us. Please keep us up to date like this. Thanks for sharing.
  • buy_cia_lis 2016/05/03 06:19 # 삭제 답글

    Great website! I am loving it!! Will be back later to read some more. I am taking your feeds also
  • buy_cia_lis 2016/05/03 06:20 # 삭제 답글

    Great website! I am loving it!! Will be back later to read some more. I am taking your feeds also
  • via_gra 2016/05/03 06:20 # 삭제 답글

    Great website! I am loving it!! Will be back later to read some more. I am taking your feeds also
  • generic 2016/05/03 06:21 # 삭제 답글

    Great website! I am loving it!! Will be back later to read some more. I am taking your feeds also
  • cia_lis_india 2016/05/03 06:21 # 삭제 답글

    Great website! I am loving it!! Will be back later to read some more. I am taking your feeds also
  • cia_lis 2016/05/03 06:22 # 삭제 답글

    insecticide permethrin side effects in cats
  • online 2016/05/03 06:25 # 삭제 답글

    insecticide permethrin side effects in cats
  • for 2016/05/06 09:34 # 삭제 답글

    I was suggested this blog by my cousin. I'm not sure whether this post is written by him as no one else know such detailed about my difficulty. You are wonderful! Thanks!
  • via_gra 2016/05/06 09:37 # 삭제 답글

    I was suggested this blog by my cousin. I'm not sure whether this post is written by him as no one else know such detailed about my difficulty. You are wonderful! Thanks!
  • cia_lis 2016/05/06 09:38 # 삭제 답글

    I was suggested this blog by my cousin. I'm not sure whether this post is written by him as no one else know such detailed about my difficulty. You are wonderful! Thanks!
  • purchase_cia_lis 2016/05/06 19:06 # 삭제 답글

    You completed a number of fine points there. I did a search on the theme and found the majority of folks will agree with your blog.
  • purchase_via_gra 2016/05/06 19:07 # 삭제 답글

    You completed a number of fine points there. I did a search on the theme and found the majority of folks will agree with your blog.
  • cia_lis 2016/05/06 19:07 # 삭제 답글

    You completed a number of fine points there. I did a search on the theme and found the majority of folks will agree with your blog.
  • via_gra 2016/05/06 19:07 # 삭제 답글

    You completed a number of fine points there. I did a search on the theme and found the majority of folks will agree with your blog.
  • for 2016/05/07 03:07 # 삭제 답글

    I am now not certain the place you're getting your info, however good topic. I needs to spend some time learning more or figuring out more. Thank you for magnificent info I was on the lookout for this information for my mission.
  • via_gra 2016/05/07 03:08 # 삭제 답글

    I am now not certain the place you're getting your info, however good topic. I needs to spend some time learning more or figuring out more. Thank you for magnificent info I was on the lookout for this information for my mission.
  • cia_lis 2016/05/07 03:08 # 삭제 답글

    I am now not certain the place you're getting your info, however good topic. I needs to spend some time learning more or figuring out more. Thank you for magnificent info I was on the lookout for this information for my mission.
  • cia_lis 2016/05/07 03:09 # 삭제 답글

    I am now not certain the place you're getting your info, however good topic. I needs to spend some time learning more or figuring out more. Thank you for magnificent info I was on the lookout for this information for my mission.
  • pharmacy 2016/05/07 03:10 # 삭제 답글

    I am now not certain the place you're getting your info, however good topic. I needs to spend some time learning more or figuring out more. Thank you for magnificent info I was on the lookout for this information for my mission.
  • cia_lis 2016/05/07 04:25 # 삭제 답글

    Great article post.Really thank you! Fantastic.
  • generic 2016/05/07 04:26 # 삭제 답글

    Great article post.Really thank you! Fantastic.
  • cia_lis_online 2016/05/07 04:26 # 삭제 답글

    Great article post.Really thank you! Fantastic.
  • via_gra_online 2016/05/07 04:26 # 삭제 답글

    Great article post.Really thank you! Fantastic.
  • cheap_cia_lis 2016/05/07 17:45 # 삭제 답글

    Really informative article post.Thanks Again. Awesome.
  • cia_lis_online 2016/05/07 17:46 # 삭제 답글

    Really informative article post.Thanks Again. Awesome.
  • cia_lis 2016/05/07 17:47 # 삭제 답글

    Really informative article post.Thanks Again. Awesome.
  • purchase_cia_lis 2016/05/07 17:48 # 삭제 답글

    Really informative article post.Thanks Again. Awesome.
  • cheap_cia_lis 2016/05/11 15:13 # 삭제 답글

    The principle isn't to artificially turn out to be effective,
  • purchase_via_gra 2016/05/11 15:14 # 삭제 답글

    The principle isn't to artificially turn out to be effective,
  • cia_lis 2016/05/15 05:30 # 삭제 답글

    It's a mammoth playground built of mountains, hills, lakes, rivers, valleys, woodlands,and beaches.
  • cia_lis_india 2016/05/18 04:18 # 삭제 답글

    I am now not certain the place you're getting your info, however good topic. I needs to spend some time learning more or figuring out more. Thank you for magnificent info I was on the lookout for this information for my mission.
  • indian_via_gra 2016/05/18 04:20 # 삭제 답글

    I am now not certain the place you're getting your info, however good topic. I needs to spend some time learning more or figuring out more. Thank you for magnificent info I was on the lookout for this information for my mission.
  • cia_lis 2016/05/18 04:23 # 삭제 답글

    I am now not certain the place you're getting your info, however good topic. I needs to spend some time learning more or figuring out more. Thank you for magnificent info I was on the lookout for this information for my mission.
  • for 2016/05/18 05:12 # 삭제 답글

    I appreciate, cause I discovered just what I used to be looking for. You have ended my four day long hunt! God Bless you man. Have a nice day. Bye
  • for 2016/05/18 05:13 # 삭제 답글

    I appreciate, cause I discovered just what I used to be looking for. You have ended my four day long hunt! God Bless you man. Have a nice day. Bye
  • side 2016/05/18 05:13 # 삭제 답글

    I appreciate, cause I discovered just what I used to be looking for. You have ended my four day long hunt! God Bless you man. Have a nice day. Bye
  • online 2016/05/18 05:13 # 삭제 답글

    I appreciate, cause I discovered just what I used to be looking for. You have ended my four day long hunt! God Bless you man. Have a nice day. Bye
  • cia_lis 2016/05/18 13:15 # 삭제 답글

    Admiring the hard work you put into your site and detailed information you offer. It's good to come across a blog every once in a while that isn't the same unwanted rehashed material. Wonderful read! I've bookmarked your site and I'm adding your RSS feeds to my Google account.
  • cia_lis 2016/05/18 13:15 # 삭제 답글

    Admiring the hard work you put into your site and detailed information you offer. It's good to come across a blog every once in a while that isn't the same unwanted rehashed material. Wonderful read! I've bookmarked your site and I'm adding your RSS feeds to my Google account.
  • online 2016/05/18 13:15 # 삭제 답글

    Admiring the hard work you put into your site and detailed information you offer. It's good to come across a blog every once in a while that isn't the same unwanted rehashed material. Wonderful read! I've bookmarked your site and I'm adding your RSS feeds to my Google account.
  • online 2016/05/18 13:15 # 삭제 답글

    Admiring the hard work you put into your site and detailed information you offer. It's good to come across a blog every once in a while that isn't the same unwanted rehashed material. Wonderful read! I've bookmarked your site and I'm adding your RSS feeds to my Google account.
  • for 2016/05/18 13:16 # 삭제 답글

    Admiring the hard work you put into your site and detailed information you offer. It's good to come across a blog every once in a while that isn't the same unwanted rehashed material. Wonderful read! I've bookmarked your site and I'm adding your RSS feeds to my Google account.
  • fast 2016/05/19 17:03 # 삭제 답글

    When some one searches for his necessary thing, so heshe desires to be available that in detail, thus that thing is maintained over here.
  • fast 2016/05/19 17:03 # 삭제 답글

    When some one searches for his necessary thing, so heshe desires to be available that in detail, thus that thing is maintained over here.
  • via_gra 2016/05/19 17:04 # 삭제 답글

    When some one searches for his necessary thing, so heshe desires to be available that in detail, thus that thing is maintained over here.
  • order_cia_lis 2016/05/19 17:04 # 삭제 답글

    When some one searches for his necessary thing, so heshe desires to be available that in detail, thus that thing is maintained over here.
  • online 2016/05/20 08:02 # 삭제 답글

    Ultimately, a dilemma that I'm passionate about. I have looked for data of this caliber for the previous various hours. Your internet site is greatly appreciated.
  • does 2016/05/20 08:02 # 삭제 답글

    Very informative post.Really thank you! Awesome.
  • does 2016/05/20 08:03 # 삭제 답글

    Very informative post.Really thank you! Awesome.
  • fast 2016/05/20 08:03 # 삭제 답글

    Ultimately, a dilemma that I'm passionate about. I have looked for data of this caliber for the previous various hours. Your internet site is greatly appreciated.
  • falls 2016/05/20 08:03 # 삭제 답글

    Very informative post.Really thank you! Awesome.
  • does 2016/05/20 08:04 # 삭제 답글

    Very informative post.Really thank you! Awesome.
  • super 2016/05/20 08:04 # 삭제 답글

    Ultimately, a dilemma that I'm passionate about. I have looked for data of this caliber for the previous various hours. Your internet site is greatly appreciated.
  • falls 2016/05/20 08:04 # 삭제 답글

    Very informative post.Really thank you! Awesome.
  • fast 2016/05/20 08:04 # 삭제 답글

    Ultimately, a dilemma that I'm passionate about. I have looked for data of this caliber for the previous various hours. Your internet site is greatly appreciated.
  • via_gra 2016/05/20 08:05 # 삭제 답글

    Ultimately, a dilemma that I'm passionate about. I have looked for data of this caliber for the previous various hours. Your internet site is greatly appreciated.
  • cia_lis 2016/05/20 15:57 # 삭제 답글

    I just couldn't depart your site before suggesting that I actually enjoyed the standard information a person provide for your visitors? Is gonna be back often in order to check up on new posts
  • cia_lis 2016/05/20 15:58 # 삭제 답글

    I just couldn't depart your site before suggesting that I actually enjoyed the standard information a person provide for your visitors? Is gonna be back often in order to check up on new posts
  • 6 2016/05/20 15:59 # 삭제 답글

    I just couldn't depart your site before suggesting that I actually enjoyed the standard information a person provide for your visitors? Is gonna be back often in order to check up on new posts
  • cia_lis 2016/05/20 16:00 # 삭제 답글

    I just couldn't depart your site before suggesting that I actually enjoyed the standard information a person provide for your visitors? Is gonna be back often in order to check up on new posts
  • cia_lis 2016/05/20 16:01 # 삭제 답글

    I just couldn't depart your site before suggesting that I actually enjoyed the standard information a person provide for your visitors? Is gonna be back often in order to check up on new posts
  • cia_lis_price 2016/05/21 13:57 # 삭제 답글

    whoah this weblog is wonderful i really like studying your posts. Keep up the great paintings! You already know, lots of individuals are searching around for this information, you can help them greatly.
  • via_gra_price 2016/05/21 14:00 # 삭제 답글

    whoah this weblog is wonderful i really like studying your posts. Keep up the great paintings! You already know, lots of individuals are searching around for this information, you can help them greatly.
  • cheap_via_gra 2016/05/23 00:50 # 삭제 답글

    Wonderful work! This is the kind of info that are meant to be shared across the internet. Disgrace on the search engines for not positioning this post higher! Come on over and consult with my website . Thank you
  • via_gra_pills 2016/05/23 00:51 # 삭제 답글

    Wonderful work! This is the kind of info that are meant to be shared across the internet. Disgrace on the search engines for not positioning this post higher! Come on over and consult with my website . Thank you
  • from 2016/05/23 00:51 # 삭제 답글

    Wonderful work! This is the kind of info that are meant to be shared across the internet. Disgrace on the search engines for not positioning this post higher! Come on over and consult with my website . Thank you
  • fast 2016/05/23 00:52 # 삭제 답글

    Wonderful work! This is the kind of info that are meant to be shared across the internet. Disgrace on the search engines for not positioning this post higher! Come on over and consult with my website . Thank you
  • cheap_cia_lis 2016/05/23 00:52 # 삭제 답글

    Wonderful work! This is the kind of info that are meant to be shared across the internet. Disgrace on the search engines for not positioning this post higher! Come on over and consult with my website . Thank you
  • buy_cia_lis 2016/05/24 10:58 # 삭제 답글

    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
  • purchase_via_gra 2016/05/24 10:59 # 삭제 답글

    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
  • purchase_cia_lis 2016/05/24 10:59 # 삭제 답글

    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
  • online 2016/05/24 11:02 # 삭제 답글

    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
  • blog 2016/05/24 13:49 # 삭제 답글

    griseofulvin psoriasis
댓글 입력 영역
◀ 다음덧글    이전덧글 ▶