2017-12-18 2 views
2

간단한 질문은 내가 기대하고프록시 나는 내 콘솔에 다음과 같은 노력하고

let a = new Proxy(new Date(), {}) 

a.getMonth(); 

를 호출 할 수 있도록하지만, 그것을 작동하지 않는 예외 :

Uncaught TypeError: this is not a Date object. at Proxy.getMonth (<anonymous>)
at <anonymous>:1:3

재미있는 부분은 크롬에서 자동 완성은 Date의 기능이 모두에 있음을 나타냅니다.. 내가 뭘 놓치고 있니? (지금

class myService { 
... 

makeProxy(data) { 
    let that = this; 
    return new Proxy (data, { 
     cache: {}, 
     original: {}, 
     get: function(target, name) { 
      let res = Reflect.get(target, name); 
      if (!this.original[name]) { 
       this.original[name] = res; 
      } 

      if (res instanceof Object && !(res instanceof Function) && target.hasOwnProperty(name)) { 
       res = this.cache[name] || (this.cache[name] = that.makeProxy(res)); 
      } 
      return res; 
     }, 
     set: function(target, name, value) { 
      var res = Reflect.set(target, name, value); 

      that.isDirty = false; 
      for (var item of Object.keys(this.original)) 
       if (this.original[item] !== target[item]) { 
        that.isDirty = true; 
        break; 
       } 

      return res; 
     } 
    }); 
} 

getData() { 
    let request = { 
    ... 
    } 
    return this._$http(request).then(res => makeProxy(res.data); 
} 

GetData의 : @Bergi

에 대한 응답

편집 나는 거기에이 코드에서 버그가 내 질문에 따로지만 여기에 내가 뭘하려고 오전 것을 깨달았) 일부 날짜가 반환됩니다

+0

프록시가 내장 객체에서 잘 작동하지 않습니다 작동합니다. 왜 당신은 날짜에 하나를 사용하려고합니까? – Bergi

+0

@Bergi [this] (https://stackoverflow.com/q/41299642/5976576)을 구현 중이며 날짜 필드가 작동하지 않습니다. – MotKohn

+0

프록시가 아니라 원래의'target'을 사용하여 호출하는 getMonth에 래퍼를 리턴해야합니다. – loganfsmyth

답변

-1

원래의 대답은 모두 잘못되었습니다. 그러나 다음과 같은 핸들러는

const handler = { 
 
     get: function(target, name) { 
 
      return name in target ? 
 
       target[name].bind(target) : undefined 
 
     } 
 
    }; 
 

 

 
    const p = new Proxy(new Date(), handler); 
 
    
 
    console.log(p.getMonth());

+0

왜 투표가 아래로 내려 갔는지는 확실하지 않지만, 그것은 문서로 이어집니다. – richbai90

+1

@ richbai90 대상에 대해 별도의 변수를 사용할 필요가 없습니다. 그리고 모든 문제는'p.getMonth()'를 작동시키는 방법입니다 - 대신'target.getMonth()'를 쓰면 대답하지 않습니다 – Bergi

+1

이 답변을 삭제하고 새로운 답변을 게시하는 것이 더 좋을 수도 있습니다. downvotes로 시작. Btw, 이것은 여전히 ​​완벽하게 작동하지 않습니다. 왜냐하면 타겟에 존재하는 속성이 아닌 * 함수 * 만 바인딩해야하기 때문입니다. – Bergi

관련 문제