2017-10-07 8 views
3

内の未定義のプロパティ「値」を設定することはできません、私はエラーを取得する -チュートリアル次ES6でコードを記述する際ES6クラス

class APromise { 
    constructor(fn) { 
    this.state = 'pending'; 
    this.value = null; 
    this.deferred = undefined; 
    fn(this.resolve); 
    } 

    resolve(newValue) { 
    this.value = newValue; // ERROR HERE 
    this.state = 'resolved'; 
    if (this.deferred) { 
     this.handle(this.deferred); 
    } 
    } 

    handle(onResolved) { 
    if (this.state == 'pending') { 
     this.deferred = onResolved; 
    } else { 
     onResolved(this.value); 
    } 
    } 

    then(onResolved) { 
    this.handle(onResolved); 
    } 
} 

const log = v => { 
    console.log(v); 
}; 
const myFun =() => { 
    return new APromise(resolve => { 
    resolve('Hello World'); 
    }); 
}; 

myFun().then(log); 

エラー -

this.value = newValue; 
     ^
TypeError: Cannot set property 'value' of undefined 

しかし、私は私の内部ですでによes6クラス、なぜこのことが定義されていないのですか?私は、デバッグとGoogleで同じ問題を探してみましたが、私は同様のもの:(

あなたは this.resolve fnに渡す

答えて

1

、あなたはそれがAPromiseインスタンスにbindに必要見つけることができません。

fn(this.resolve.bind(this)); 

デモ:

class APromise { 
 
    constructor(fn) { 
 
    this.state = 'pending'; 
 
    this.value = null; 
 
    this.deferred = undefined; 
 
    fn(this.resolve.bind(this)); 
 
    } 
 

 
    resolve(newValue) { 
 
    this.value = newValue; // ERROR HERE 
 
    this.state = 'resolved'; 
 
    if (this.deferred) { 
 
     this.handle(this.deferred); 
 
    } 
 
    } 
 

 
    handle(onResolved) { 
 
    if (this.state == 'pending') { 
 
     this.deferred = onResolved; 
 
    } else { 
 
     onResolved(this.value); 
 
    } 
 
    } 
 

 
    then(onResolved) { 
 
    this.handle(onResolved); 
 
    } 
 
} 
 

 
const log = v => { 
 
    console.log(v); 
 
}; 
 
const myFun =() => { 
 
    return new APromise(resolve => { 
 
    resolve('Hello World'); 
 
    }); 
 
}; 
 

 
myFun().then(log);