2017-05-22 11 views
0

私のcreateCon関数はthisを使用してこのオブジェクトのconを設定します。私はこれを未定義にしています。エラー:未定義の 'con'のプロパティを設定できません。 これはオブジェクト関数からこれを参照できるのは何ですか?拡張子関数は 'this'を使用できません、キーワードは定義されていません

class parent { 
    constructor(stringA, stringB){ 
     this.config = {}; 
     this.con = {}; 
    } 
} 

class child extends parent { 
    constructor(stringA, stringB) { 
     super(stringA,stringB) 
     this.config = { 
      full : stringA+stringB 
     } 
    } 

    createConn(){ 
     var con = con(this.config.full); 
     con.connect(function(err){ 
      if(!err) this.con = con; 
     }) 
    } 
} 
+0

@MikeMcCaughanこれは範囲の問題ではありません。それは拘束力のある問題です。 'this'の動作は変数スコープとは別に指定されます。 – slebetman

答えて

1

あなたはfunctionの内部thisキーワードを使用しています。 thisは他のOOP言語と似ておらず、関数の実行に基づいて変更できる 'コンテキスト'を参照します。

矢印機能が定義されているコンテキストの字句的にバインド(つまり、保持)する矢印機能を使用します。

createConn(){ 
    var con = con(this.config.full); 
    con.connect((err) => { 
     if(!err) this.con = con; 
    }) 
}