2017-11-06 6 views
0

だから、私はこの悪夢のコードを完全にうまくいき、クラスに入れました。しかし、それは)(楽しいなし(:-(約束のエラーを投げ始め、それが正常に動作機能約束と悪夢JSのクラス

class test { 
 
    constructor() { 
 
    this.init(() => { 
 
     this.start() 
 
    }) 
 
    } 
 

 
    init() { 
 
    this.nightmare = new Nightmare({ 
 
     show: true, 
 
     typeInterval: 20, 
 
     openDevTools: { 
 
     detach: true 
 
     } 
 
    }); 
 
    } 
 

 
    async start() { 
 

 
    await this.nightmare 
 
     .useragent(userAgent) 
 
     .goto("https://www.yahoo.com") 
 

 
    fun(); 
 

 
    async function fun() { 
 
     await this.nightmare.goto('https://google.com') 
 
    } 
 
    } 
 
} 
 

 
new test().start();

エラーがある:これは本当にありません

(node:1101) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'nightmare' of undefined

(node:1101) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

+0

) '' try catch ' – dzm

+0

あなたは 'await fun();'を試みましたか?関数の初期化後に呼び出しを移動するとどうなりますか? –

答えて

1

約束しているか待っているかthisfun()の中のあなたのオブジェクトを参照していないのでエラーが発生していますあなたが関数を作成して呼び出すときは、fun()あなたのオブジェクトへの参照が失われます。this考えてみましょう:

class test { 
 
    constructor() { 
 
     this.init() 
 
    } 
 
    
 
    init() { 
 
     this.prop = "a property" 
 
    } 
 
    start() { 
 
     console.log("this outside of fun: ", this) 
 
     fun() 
 
     function fun(){ 
 
      console.log("this in fun:", this) 
 
     } 
 
    } 
 
}  
 
new test().start()

あなたはthisfun()で定義されていないことがわかります。

fun()本当の方法を行うことを検討し、また、手動のようなものでthisをバインドすることができthis.fun()とそれを呼び出す:あなた `this.nightmare.gotoを待つ(「https://google.com」をラップ

fun.call(this)