2017-05-23 7 views
0

내가 그러나 I가 this에 문제 데 바벨-polyfill/바벨 프리셋-es2017와 비동기 함수 방법을 사용하는 객체를 생성 비동기 객체 메소드 내측이 :

let obj =() => { 
    return { 
     doAsync: async() => { 
      let thing = await longProcess() 
      return this.transform(thing) 
     }, 

     transform: (thing) => { 
      return psuedoCodeTransform(thing) 
     } 
    } 
} 

let instance = obj() 
instance.doAsync() 
// TypeError: cannot read property 'transform' of undefined`. 

에 설명이 뭔가 ES2017, babel-polyfill/regenerator 런 타임 잡았습니까?

+0

이 화살표의 기능을 가진'async' /'await' 모든 것을 함께 할 수 없다. – Bergi

+0

ES7! == ES2017 ... –

답변

2

Arrow functions do not create their own context. 그들은 자신의 thisthis을 가지지 않으므로 엔 클로징 스코프의 컨텍스트를 참조하게됩니다. 이 경우 (말장난 없음) thisinstance과 동일한 개체를 전혀 참조하지 않습니다.

doAsyncthis을 기록하면 window입니다.

+0

흥미 롭습니다. Angular 서비스 생성자 안에서이 일을하고 있는데,'console.log (this) // undefined'를 주었다. 그것이 저를 버렸습니다. –

1

조셉 드리머의 반응은 분명히 분명합니다.하지만 제가 가장 잘 수행 한 예제는 다음과 같습니다. 코드가 변경되어 작동하도록해야합니다. 유일한 변화가 실제로 대신 화살표 기능의 정상적인 기능으로 doAsync을 정의하는주의 :

let obj =() => { 
    return { 
     doAsync: async function() { 
      let thing = await longProcess() 
      return this.transform(thing) 
     }, 

     transform: (thing) => { 
      return psuedoCodeTransform(thing) 
     } 
    } 
} 

let instance = obj() 
instance.doAsync() 
// TypeError: cannot read property 'transform' of undefined`. 
+0

또는 단순히'async doAsync() {...}'. 왜 누군가가 객체 리터럴에서 화살표 함수를 사용하려고하는지 이해하지 못합니다 (물론 'this'는 제외). 메소드 정의가 더 짧습니다. –