2015-06-09 2 views
0

У меня есть две функции:Обещания и доступ к этим

p.test = 'test'; 

p.functionA = function(){ 

    console.log('function A'); 
    var dfd = new $.Deferred(); 

    setInterval(function(){dfd.resolve();}, 2000); 

    return dfd.promise(); 

}; 


p.functionB = function(){ 

    console.log('function B'); 
    console.log(this.test); 
    var dfd = new $.Deferred(); 

    setInterval(function(){dfd.resolve();}, 2000); 

    return dfd.promise(); 
}; 

функции называются так:

this.functionA().then(this.functionB); 

я желаю, чтобы получить значение теста в функции B пока она не определена. Зачем? Как я могу получить к нему доступ?

+2

'это .functionA(). then (this.functionB.bind (this)); ' – Sirko

+0

Если у меня есть число .then(), мне нужно будет связывать каждый раз, например. this.functionA(), а затем (this.functionB.bind (это)), а затем (this.functionC.bind (это)), а затем (this.functionD.bind (это))...; – panthro

ответ

3

Вы можете bind контекст для функции:

this.functionA().then(this.functionB.bind(this)); 

Если вы хотите поддержать IE8 и не хотят использовать bind polyfill, вы можете также использовать jQuery's proxy:

this.functionA().then($.proxy(this.functionB, this)); 

Если вы не хотите повторять это, вы также можете использовать более полную библиотеку Promise, такую ​​как Bluebird. Вам нужно будет обновить значение возврата для возврата доверенного обещания:

return Promise.resolve(dfd.promise()). 

Тогда вы могли бы использовать:

Promise.bind(this).then(this.functionA).then(this.functionB). ... 
0

Попробуйте с использованием deferred.resolveWith()

var p = {}; 
 

 
p.test = 'test'; 
 

 
p.functionA = function() { 
 

 
    console.log('function A'); 
 
    var dfd = new $.Deferred(); 
 

 
    setTimeout(function() { 
 
    // set context : `this` of returned jQuery promise to `p` 
 
    dfd.resolveWith(p); 
 
    }, 2000); 
 

 
    return dfd.promise(); 
 

 
}; 
 

 

 
p.functionB = function() { 
 
    // `this`: `p` 
 
    console.log('function B'); 
 
    console.log(this.test); 
 
    var dfd = new $.Deferred(); 
 

 
    setTimeout(function() { 
 
    dfd.resolve(); 
 
    }, 2000); 
 

 
    return dfd.promise(); 
 
}; 
 

 
p.functionA().then(p.functionB);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> 
 
</script>

Смежные вопросы