기본 콘텐츠로 건너뛰기

라벨이 function인 게시물 표시

[삽질주의] js에선 object를 어떻게 확장하는가? .map 만들기.

http://spectrum.egloos.com/5580651 옛날 글 소환인데 map을 object 에서도 한번 해볼려고 이렇게 시도해 보았다. > Object.defineProperty(Object.prototype, "map", {value: function(fn) {   for (idx in this) this[idx]=fn(this[idx]); return this; } }); > q={a:1, b:2} > q.map(v=>v+1) Object {a: 2, b: 3} ECMA5부터 Object.defineProperty 를 쓸 수 있고 prototype 삽질을 막을 수 있다. > q={a:1, b: {c: 2, d: 4}} > Object.defineProperty(Object.prototype, "map", {value: function(fn) {   let map=(f,arr)=>{     for (idx in arr)         arr[idx]=typeof arr[idx]==="object" && map(f,arr[idx]) || f(arr[idx]);     return arr;   }   return map(fn, this); }}); > q.map(v=>v+1) Object {a: 2, b: Object} a:2 b:Object   c:3   d:5 뭐 의도한대로 잘 나오긴 한다. value 인 경우만 fn을 실행하고 object면 재귀를 사용한다. 뭐 array만 들어와도 이건 망하겠네; google 에서 왜 [[a,2], [b,3]] 따위 자료 구조를 썼는지 어느정도 이해가 된다.

Template events 안에서 function 사용팁

Template events안에서 function을 쓸 때 global scope 으로 쓰는 게 싫으셨죠? var clickProcess = function(e) { ... }; Template.nono.events({ 'click .button': function(e, tmpl) { clickProcess(e); ... }, 'touchend .button': function(e, tmpl) { clickProcess(e); ... } }); 이렇게 쓰지 말고 Template.nono scope 안으로 가둡시다. Template.nono.clickProcess = function(e) { ... } 그러고 나서 event 안에선 tmpl.view.template 으로 참조하면 Template.nono 자신을 가져올 수 있습니다! Template.nono.events({ 'click .button': function(e, tmpl) { tmpl.view.template.clickProcess(e); ... }, 'touchend .button': function(e, tmpl) { tmpl.view.template.clickProcess(e); ... } }); 더 이상 글로벌 스코프로 인한 불안에 떨지마세요~