기본 콘텐츠로 건너뛰기

왜 object에 prototype을 쓰지 않나?




이유는 이렇다.
prototype 에 method 를 정의하면
자기 자신도 해당 object 에 카운트가 된다.

무슨말이냐?
object (array포함) 의 key와 value를 보기 위해 종종 아래와 같이 해본다.
var ages = {  John: 10,  Mary: 28,  Alice: 16};
일때
(function(obj){ for (idx in obj) { console.log(idx+':'+obj[idx]) }})(ages) 
이렇게 떠 보면
John:30
Mary:30
Alice:30
뭐 이렇게 나오겠지.

그럼 아예 object 에 이걸 prototype 해서 그냥 method 로 만들지 싶어

Object.prototype.printObject=function(){ for (idx in this) { console.log(idx+':'+this[idx]) }};
요따우로 해주면

ages.printObject()
> John:10
> Mary:20
> Alice:30
> printObject:function (){ for (idx in this) { console.log(idx+':'+this[idx]) }}

망한다.
다시 이야기 하지만 자기 자신도 객체의 일부가 되니까.
그래서 쓰지말라는 것이다.

hasOwnProperty를 사용해서 피해가는 방법도 있겠지만 다른 문제가 있다.
자세한 설명은 생략한다. 왜 그런지 알고 싶으면 본문 봐라. (난 알고싶지 않아서 안봤다. 안쓸거니까 우왕ㅋ)

결론은 이거다.
defineProperty 를 사용하자.
ECMAScript 5 스펙이다. 하지만 망할 IE7 에선 안되겠지
http://ejohn.org/blog/ecmascript-5-objects-and-properties/ (꼼꼼히 읽어볼 필요가 있다)
사용법이 좀 뜨억함.

Object.defineProperty(Object.prototype, "printObject", {
  value: function() {
    for (idx in this) { console.log(idx+':'+this[idx]) }
  }
});

이런식으로 쓰면 된다.
console.log 를 찍은 삽질을 해도 이해바란다.

---------- 보너스 ---------
get 으로 합을 구해보자.
array 형인 경우 length 라는 property 가 있어서 항상 갯수를 반환한다.
length() 가 아니고 length 로 말이다.

[10,20,30].length() <- 이게 아니다.
[10,20,30].length <- 요거

그렇다. getter를 정의한 것이다. 그럼 sum이 getter 로 선언하면 되는데.

일단 sum은 어떻게 구하는가?
reduce를 사용해본다. noSQL! 하고 외친다면 당신이 생각하는 그것이 맞다고 말해주고 싶다.

var ages = [10,20,30];
ages.reduce(function(sum,val) { return sum+val; });
> 60

Object.defineProperty(Object.prototype, "sum", {
  get: function() {
    return this.reduce(function(sum,val) { return sum+val; });
  }
});

ages.sum
> 60

좋지 아니한가?

댓글

이 블로그의 인기 게시물

세상 간단한 https(+secured websocket): Caddy

nginx, apache2 같은 걸로 매번 certbot 연동을 통해 https 하는게 지겨워서 알아보니 Caddy라는게 있더라. 설치법은 강하게 크기 위해 알아서 해본다. # cat /etc/caddy/Caddyfile your.shitty.site:8123 {   proxy / localhost:9123 {     websocket     transparent   } } 이건 외부에서 8123으로 들어오는 걸 내부적으로 9123로 맞춰서 https 맞춰주는 reverse proxy. 만일 port를 생략하면 # cat /etc/caddy/Caddyfile your.shitty.site {   proxy / localhost:9123 {     websocket     transparent   } } 기본포트인 443으로 되어 https://your.shitty.site 로 접속이 된다. 요새 말썽이던 cloudflare 버리고 netlify domain이랑 caddy를 쓰니까 앓던 이가 빠진 느낌. 이 조합은 당분간 계속 써야겠다 싶다.

저지연 오디오 생성 LLVC 사용기

https://github.com/KoeAI/LLVC 써봄 CUDA 11.8 버전 쓰고 있어 pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 VC 없어서 설치 https://wikidocs.net/168848 참조 FAIRSEQ 관련 오류 https://github.com/facebookresearch/fairseq/issues/2908 pip install editdistance  설치 No CUDA runtime is found, using CUDA_HOME='C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8' 오류 멀쩡하게 있는데 안됨. pip install torch==2.1.0+cu118 torchvision==0.16.0+cu118 torchaudio==2.1.0+cu118 --extra-index-url https://download.pytorch.org/whl/cu118 다시 설치 set DISTUTILS_USE_SDK=1 이게 문젠가 설정하고 재도전 Using cached ruamel.yaml.clib-0.2.8-cp311-cp311-win_amd64.whl (118 kB) Building wheels for collected packages: fairseq   Building wheel for fairseq (pyproject.toml) ... error   error: subprocess-exited-with-error   × Building wheel for fairseq (pyproject.toml) did not run successfully.   │ exit code: 1   ╰─> [1829 lines of output]       No CUDA runtime is found, usi...