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

핑백

덧글

  • purchase_via_gra 2016/05/30 17:16 # 삭제 답글

    Wow! This blog looks exactly like my old one! It's on a completely different topic but it has pretty much the same page layout and design. Excellent choice of colors!
  • cia_lis 2016/05/31 08:01 # 삭제 답글

    You're so interesting! I don't think I have read anything like this before. So wonderful to discover somebody with some unique thoughts on this subject matter. Seriously.. thank you for starting this up. This website is one thing that is needed on the internet, someone with a bit of originality!
  • cia_lis 2016/05/31 08:02 # 삭제 답글

    You're so interesting! I don't think I have read anything like this before. So wonderful to discover somebody with some unique thoughts on this subject matter. Seriously.. thank you for starting this up. This website is one thing that is needed on the internet, someone with a bit of originality!
  • cia_lis 2016/05/31 08:03 # 삭제 답글

    You're so interesting! I don't think I have read anything like this before. So wonderful to discover somebody with some unique thoughts on this subject matter. Seriously.. thank you for starting this up. This website is one thing that is needed on the internet, someone with a bit of originality!
  • from 2016/05/31 08:04 # 삭제 답글

    You're so interesting! I don't think I have read anything like this before. So wonderful to discover somebody with some unique thoughts on this subject matter. Seriously.. thank you for starting this up. This website is one thing that is needed on the internet, someone with a bit of originality!
  • tadalafil 2016/05/31 19:38 # 삭제 답글

    Regards for helping out, superb information.
  • cia_lis 2016/05/31 19:38 # 삭제 답글

    Regards for helping out, superb information.
  • for 2016/05/31 19:38 # 삭제 답글

    Regards for helping out, superb information.
  • fast 2016/05/31 19:39 # 삭제 답글

    Regards for helping out, superb information.
  • cia_lis 2016/05/31 19:39 # 삭제 답글

    Regards for helping out, superb information.
  • cia_lis 2016/06/01 11:16 # 삭제 답글

    This kind of game gives a real experience of
  • cia_lis 2016/06/01 11:17 # 삭제 답글

    This kind of game gives a real experience of
  • via_gra 2016/06/01 11:17 # 삭제 답글

    This kind of game gives a real experience of
  • cia_lis 2016/06/01 11:18 # 삭제 답글

    This kind of game gives a real experience of
  • cia_lis 2016/06/01 11:18 # 삭제 답글

    This kind of game gives a real experience of
  • cia_lis_pills 2016/06/05 09:02 # 삭제 답글

    Wow! This could be one particular of the most useful blogs We've ever arrive across on this subject. Actually Excellent. I'm also an expert in this topic so I can understand your hard work.
  • via_gra 2016/06/05 09:02 # 삭제 답글

    Wow! This could be one particular of the most useful blogs We've ever arrive across on this subject. Actually Excellent. I'm also an expert in this topic so I can understand your hard work.
  • cia_lis 2016/06/05 09:03 # 삭제 답글

    Wow! This could be one particular of the most useful blogs We've ever arrive across on this subject. Actually Excellent. I'm also an expert in this topic so I can understand your hard work.
  • buy_via_gra 2016/06/05 09:03 # 삭제 답글

    Wow! This could be one particular of the most useful blogs We've ever arrive across on this subject. Actually Excellent. I'm also an expert in this topic so I can understand your hard work.
  • cia_lis 2016/06/12 07:23 # 삭제 답글

    what are some superior and in demand websites for blogs? ?? .
  • via_gra 2016/06/12 07:24 # 삭제 답글

    what are some superior and in demand websites for blogs? ?? .
  • via_gra_pills 2016/06/12 07:24 # 삭제 답글

    what are some superior and in demand websites for blogs? ?? .
  • via_gra_pills 2016/06/12 07:25 # 삭제 답글

    what are some superior and in demand websites for blogs? ?? .
  • cia_lis 2016/06/12 07:25 # 삭제 답글

    what are some superior and in demand websites for blogs? ?? .
  • online 2016/06/14 20:32 # 삭제 답글

    I have learn some good stuff here. Certainly price bookmarking for revisiting.
  • online 2016/06/14 20:32 # 삭제 답글

    I have learn some good stuff here. Certainly price bookmarking for revisiting.
  • online 2016/06/14 20:32 # 삭제 답글

    I have learn some good stuff here. Certainly price bookmarking for revisiting.
  • cia_lis 2016/06/14 20:32 # 삭제 답글

    I have learn some good stuff here. Certainly price bookmarking for revisiting.
  • for 2016/06/14 20:33 # 삭제 답글

    I have learn some good stuff here. Certainly price bookmarking for revisiting.
  • online 2016/06/15 19:07 # 삭제 답글

    Hey very nice web site!! Man.. Beautiful.. Wonderful.. I'll bookmark your web site and take the feeds alsoKI am satisfied to seek out a lot of helpful information here in the publish, we want work out extra techniques in this regard, thank you for sharing
  • via_gra 2016/06/15 19:07 # 삭제 답글

    Hey very nice web site!! Man.. Beautiful.. Wonderful.. I'll bookmark your web site and take the feeds alsoKI am satisfied to seek out a lot of helpful information here in the publish, we want work out extra techniques in this regard, thank you for sharing
  • cia_lis 2016/06/15 19:08 # 삭제 답글

    Hey very nice web site!! Man.. Beautiful.. Wonderful.. I'll bookmark your web site and take the feeds alsoKI am satisfied to seek out a lot of helpful information here in the publish, we want work out extra techniques in this regard, thank you for sharing
  • cia_lis 2016/06/15 19:08 # 삭제 답글

    Hey very nice web site!! Man.. Beautiful.. Wonderful.. I'll bookmark your web site and take the feeds alsoKI am satisfied to seek out a lot of helpful information here in the publish, we want work out extra techniques in this regard, thank you for sharing
  • online 2016/06/15 19:08 # 삭제 답글

    Hey very nice web site!! Man.. Beautiful.. Wonderful.. I'll bookmark your web site and take the feeds alsoKI am satisfied to seek out a lot of helpful information here in the publish, we want work out extra techniques in this regard, thank you for sharing
  • for 2016/06/16 09:56 # 삭제 답글

    There is numerous separate years Los angeles Weight reduction eating plan with each a person can be a necessity. The pioneer part can be your original obtaining rid of belonging towards the extra pounds. la weight loss
  • cia_lis_online 2016/06/16 09:56 # 삭제 답글

    There is numerous separate years Los angeles Weight reduction eating plan with each a person can be a necessity. The pioneer part can be your original obtaining rid of belonging towards the extra pounds. la weight loss
  • generic_cia_lis 2016/06/16 09:56 # 삭제 답글

    There is numerous separate years Los angeles Weight reduction eating plan with each a person can be a necessity. The pioneer part can be your original obtaining rid of belonging towards the extra pounds. la weight loss
  • cia_lis 2016/06/16 09:57 # 삭제 답글

    There is numerous separate years Los angeles Weight reduction eating plan with each a person can be a necessity. The pioneer part can be your original obtaining rid of belonging towards the extra pounds. la weight loss
  • purchase_cia_lis 2016/06/16 09:57 # 삭제 답글

    There is numerous separate years Los angeles Weight reduction eating plan with each a person can be a necessity. The pioneer part can be your original obtaining rid of belonging towards the extra pounds. la weight loss
  • cia_lis_dosage 2016/06/16 16:32 # 삭제 답글

    Very well written article. It will be helpful to anyone who usess it, as well as yours truly
  • without 2016/06/16 16:33 # 삭제 답글

    Very well written article. It will be helpful to anyone who usess it, as well as yours truly
  • tadalafil 2016/06/16 16:33 # 삭제 답글

    Very well written article. It will be helpful to anyone who usess it, as well as yours truly
  • via_gra 2016/06/16 16:34 # 삭제 답글

    Very well written article. It will be helpful to anyone who usess it, as well as yours truly
  • sildenafil_citrate 2016/06/16 16:34 # 삭제 답글

    Very well written article. It will be helpful to anyone who usess it, as well as yours truly
  • cia_lis 2016/06/21 21:27 # 삭제 답글

    Your goal is to breed all the different dragons
  • via_gra 2016/06/21 21:27 # 삭제 답글

    Your goal is to breed all the different dragons
  • cia_lis 2016/06/21 21:28 # 삭제 답글

    Your goal is to breed all the different dragons
  • via_gra 2016/06/21 21:28 # 삭제 답글

    Your goal is to breed all the different dragons
  • generic 2016/06/24 02:26 # 삭제 답글

    It's truly a great and useful piece of information. I'm satisfied that you shared this helpful information with us. Please stay us informed like this. Thank you for sharing.
  • via_gra 2016/06/24 02:27 # 삭제 답글

    It's truly a great and useful piece of information. I'm satisfied that you shared this helpful information with us. Please stay us informed like this. Thank you for sharing.
  • generic 2016/06/24 02:27 # 삭제 답글

    It's truly a great and useful piece of information. I'm satisfied that you shared this helpful information with us. Please stay us informed like this. Thank you for sharing.
  • via_gra 2016/06/24 02:27 # 삭제 답글

    It's truly a great and useful piece of information. I'm satisfied that you shared this helpful information with us. Please stay us informed like this. Thank you for sharing.
  • cia_lis 2016/06/25 08:19 # 삭제 답글

    Hello, i think that i saw you visited my blog thus i got here to return the choose.I am trying to to find issues to enhance my site!I guess its adequate to use a few of your ideas!!
  • female_via_gra 2016/06/25 08:19 # 삭제 답글

    Hello, i think that i saw you visited my blog thus i got here to return the choose.I am trying to to find issues to enhance my site!I guess its adequate to use a few of your ideas!!
  • cia_lis 2016/06/25 08:20 # 삭제 답글

    Hello, i think that i saw you visited my blog thus i got here to return the choose.I am trying to to find issues to enhance my site!I guess its adequate to use a few of your ideas!!
  • female_via_gra 2016/06/25 08:20 # 삭제 답글

    Hello, i think that i saw you visited my blog thus i got here to return the choose.I am trying to to find issues to enhance my site!I guess its adequate to use a few of your ideas!!
  • cia_lis 2016/06/29 15:47 # 삭제 답글

    Merely a smiling visitor here to share the love , btw outstanding style. Audacity, a lot more audacity and always audacity. by Georges Jacques Danton.
  • place 2016/06/29 15:47 # 삭제 답글

    Merely a smiling visitor here to share the love , btw outstanding style. Audacity, a lot more audacity and always audacity. by Georges Jacques Danton.
  • cia_lis 2016/06/29 15:48 # 삭제 답글

    Merely a smiling visitor here to share the love , btw outstanding style. Audacity, a lot more audacity and always audacity. by Georges Jacques Danton.
  • place 2016/06/29 15:48 # 삭제 답글

    Merely a smiling visitor here to share the love , btw outstanding style. Audacity, a lot more audacity and always audacity. by Georges Jacques Danton.
  • cia_lis_price 2016/07/01 11:20 # 삭제 답글

    Great article post.Really thank you! Fantastic.
  • cia_lis 2016/07/01 11:20 # 삭제 답글

    Wow, awesome blog layout! How long have you been blogging
  • cia_lis 2016/07/01 11:20 # 삭제 답글

    Wow, awesome blog layout! How long have you been blogging
  • cia_lis 2016/07/01 11:21 # 삭제 답글

    Wow, awesome blog layout! How long have you been blogging
  • cia_lis 2016/07/01 11:21 # 삭제 답글

    Wow, awesome blog layout! How long have you been blogging
  • cia_lis 2016/07/01 11:21 # 삭제 답글

    Wow, awesome blog layout! How long have you been blogging
  • via_gra_price 2016/07/01 11:24 # 삭제 답글

    Great article post.Really thank you! Fantastic.
  • buy_cia_lis 2016/07/08 22:23 # 삭제 답글

    Im genuinely enjoying the style and layout of one's website. Its a very uncomplicated on the eyes which makes it a great deal much more enjoyable for me to come here and pay a visit to far more typically. Did you hire out a designer to make your theme? Excellent perform!
  • cia_lis 2016/07/08 22:24 # 삭제 답글

    Im genuinely enjoying the style and layout of one's website. Its a very uncomplicated on the eyes which makes it a great deal much more enjoyable for me to come here and pay a visit to far more typically. Did you hire out a designer to make your theme? Excellent perform!
  • via_gra 2016/07/08 22:24 # 삭제 답글

    Im genuinely enjoying the style and layout of one's website. Its a very uncomplicated on the eyes which makes it a great deal much more enjoyable for me to come here and pay a visit to far more typically. Did you hire out a designer to make your theme? Excellent perform!
  • purchase_via_gra 2016/07/08 22:24 # 삭제 답글

    Im genuinely enjoying the style and layout of one's website. Its a very uncomplicated on the eyes which makes it a great deal much more enjoyable for me to come here and pay a visit to far more typically. Did you hire out a designer to make your theme? Excellent perform!
  • fast 2016/07/08 22:25 # 삭제 답글

    Im genuinely enjoying the style and layout of one's website. Its a very uncomplicated on the eyes which makes it a great deal much more enjoyable for me to come here and pay a visit to far more typically. Did you hire out a designer to make your theme? Excellent perform!
  • cia_lis 2016/07/12 00:24 # 삭제 답글

    When I originally commented I clicked the Notify me when new comments are added checkbox and now every time a comment is added I get 4 emails using the same comment. Is there any way you may take away me from that service? Thanks!
  • via_gra_sale 2016/07/12 00:24 # 삭제 답글

    When I originally commented I clicked the Notify me when new comments are added checkbox and now every time a comment is added I get 4 emails using the same comment. Is there any way you may take away me from that service? Thanks!
  • cia_lis 2016/07/12 00:25 # 삭제 답글

    When I originally commented I clicked the Notify me when new comments are added checkbox and now every time a comment is added I get 4 emails using the same comment. Is there any way you may take away me from that service? Thanks!
  • via_gra_sale 2016/07/12 00:26 # 삭제 답글

    When I originally commented I clicked the Notify me when new comments are added checkbox and now every time a comment is added I get 4 emails using the same comment. Is there any way you may take away me from that service? Thanks!
  • cia_lis 2016/07/12 05:53 # 삭제 답글

    Though it is true I enjoy your writing style, I don't agree with your main point of view about this one. I do delight in your website nevertheless.
  • order_cia_lis 2016/07/12 05:54 # 삭제 답글

    Though it is true I enjoy your writing style, I don't agree with your main point of view about this one. I do delight in your website nevertheless.
  • cia_lis_sale 2016/07/12 05:54 # 삭제 답글

    Though it is true I enjoy your writing style, I don't agree with your main point of view about this one. I do delight in your website nevertheless.
  • purchase_cia_lis 2016/07/12 05:55 # 삭제 답글

    Though it is true I enjoy your writing style, I don't agree with your main point of view about this one. I do delight in your website nevertheless.
  • online 2016/07/12 05:56 # 삭제 답글

    Though it is true I enjoy your writing style, I don't agree with your main point of view about this one. I do delight in your website nevertheless.
  • cheap_via_gra 2016/07/14 08:06 # 삭제 답글

    Definitely pent subject material, be thankful in support of picky facts .
  • purchase_cia_lis 2016/07/14 08:06 # 삭제 답글

    Definitely pent subject material, be thankful in support of picky facts .
  • via_gra 2016/07/14 08:07 # 삭제 답글

    Definitely pent subject material, be thankful in support of picky facts .
  • purchase_cia_lis 2016/07/14 08:07 # 삭제 답글

    Definitely pent subject material, be thankful in support of picky facts .
  • purchase_via_gra 2016/07/14 08:08 # 삭제 답글

    Definitely pent subject material, be thankful in support of picky facts .
  • cia_lis_price 2016/07/23 12:01 # 삭제 답글

    It is also possible that Zynga's chosen advertising
  • via_gra_price 2016/07/23 12:01 # 삭제 답글

    It is also possible that Zynga's chosen advertising
  • cia_lis 2016/07/23 12:02 # 삭제 답글

    It is also possible that Zynga's chosen advertising
  • via_gra 2016/07/23 12:02 # 삭제 답글

    It is also possible that Zynga's chosen advertising
  • cheap 2016/07/26 11:33 # 삭제 답글

    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!
  • dosage 2016/07/26 11:35 # 삭제 답글

    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!
  • cheap 2016/07/26 11:35 # 삭제 답글

    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!
  • dosage 2016/07/26 11:36 # 삭제 답글

    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!
  • dosage 2016/07/26 11:37 # 삭제 답글

    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!
  • via_gra 2016/07/26 20:12 # 삭제 답글

    Thanks so much for sharing all with the awesome info! I am looking forward to checking out far more posts!
  • cia_lis 2016/07/26 20:13 # 삭제 답글

    Thanks so much for sharing all with the awesome info! I am looking forward to checking out far more posts!
  • place 2016/07/26 20:13 # 삭제 답글

    Thanks so much for sharing all with the awesome info! I am looking forward to checking out far more posts!
  • buy_cia_lis 2016/07/26 20:14 # 삭제 답글

    Thanks so much for sharing all with the awesome info! I am looking forward to checking out far more posts!
  • tadalafil 2016/07/26 20:14 # 삭제 답글

    Thanks so much for sharing all with the awesome info! I am looking forward to checking out far more posts!
댓글 입력 영역
◀ 다음덧글    이전덧글 ▶