2016-04-19 36 views
-1

當我打電話從一個回調的ES6類的方法,我可以不再引用this作爲我的對象:在ES6類這個/自

class store{ 
    constructor(){ 
    this.value = 10; 
    }; 

    printValue(self){ 
    console.log(this); 
    console.log(self);//the value that I want print 
    }; 
}; 

class undefinedClass{ 
    constructor(store){ 
    this.store = store; 
    }; 

    storeQuery(){ 
    let ff = this.store.printValue; 
    setTimeout(ff, 300, this.store); 
    }; 
}; 

let i = new store(); 
let b = new undefinedClass(i); 
b.storeQuery(); 

當我打電話b.storeQuery()THA值我想要打印是第二個。 有沒有更好的方法來做到這一點?

+0

你似乎並不被傳遞'self'參數爲'printValue' ..它應該等於什麼? – Tuvia

+0

請參閱[如何在回調中訪問正確的'this' /上下文?](http://stackoverflow.com/q/20279484/218196) –

回答

0

由於@alex說,有.bind

的文檔是here

class store{ 
 
    constructor(){ 
 
    this.value = 10; 
 
    }; 
 

 
    printValue(){ 
 
    
 
    console.log(this.value);//the value that I want print 
 
    }; 
 
}; 
 

 
class undefinedClass{ 
 
    constructor(store){ 
 
    this.store = store; 
 
    }; 
 

 
    storeQuery(){ 
 
    setTimeout(this.store.printValue.bind(this.store), 300); 
 
    }; 
 
}; 
 

 

 
let i = new store(); 
 
let b = new undefinedClass(i); 
 

 
    
 
b.storeQuery();

0

當您在JavaScript中使用對象的函數引用時,它將失去將其設置爲該對象的ThisBinding。

您可以將ThisBinding改爲任何使用Function.prototype.bind()的東西。

在這種情況下,你會使用類似ff.bind(this.store)

+0

亞歷克斯 - 請在這裏看到我的評論:http:// stackoverflow。 com/questions/36722798/this-self-in-es6-class#comment61030536_36722798你如何解決這個問題? – Tuvia

+0

或使用箭頭功能。無論如何,'printValue'需要一個參數。 – zeroflagL