试图让这个变得简单一点:
//first named function
function tryMe(x){
tryMeAgain(x);
};
//second named function
function tryMeAgain(y){
return y;
};
//assign the result of first function (which will actually be the result of the second function) to a var
var testTry = tryMe('worth a shot');
console.log(testTry); //undefined! But I would like 'testTry' to return 'worth a shot'
所以我有两个问题:
- 这是为什么?
- 如何正确分配“testTry”?
EDIT BELOW: So the responses all make sense and I think my problem may lay somewhere else in my code. My attempt to simplify the question may have overlooked another piece of the puzzle. I'm including a new version and hoping you all can shed some light:
var runtime = (function(){
var $jq = jQuery.noConflict(true);
function Runtime(){
this.$jq = $jq;
}
Runtime.prototype.method1 = function( _value, _callback ){
setTimeout(function(){ console.log('dependency1_resolved');
_callback.apply(this, [{valIs:_value}]);
}.bind(this), (Math.random() * 1000));
};
Runtime.prototype.method2 = function( _value, _callback ){
var self = this;
setTimeout(function(){ console.log('dependency2_resolved');
_callback.apply(self, [{differntValIs:3}]);
}.bind(this), (Math.random() * 1000));
};
Runtime.prototype.method3 = function( _value, _callback ){
setTimeout(function(){ console.log('dependency3_resolved');
_callback.apply(this, [{valIs:_value['differntValIs'] *= 4}]);
}.bind(this), (Math.random() * 1000));
};
return new Runtime();
})();
runtime.initialize(function( $ ){
function firstCalc(firstInput){
return runtime.method1(firstInput,secondCalc);
};
function secondCalc(secondInput){
return runtime.method2(secondInput, thirdCalc);
};
function thirdCalc(thirdInput){
return runtime.method3(thirdInput, fourthCalc);
};
function fourthCalc(ourResult){
//console.log( ourResult );
return ourResult;
};
var _value = firstCalc(4); //this is undefined!!
});
最佳答案
您从 tryMeAgain
返回值,而不是从 tryMe
方法返回值,因此返回的默认值是 undefined
//first named function
function tryMe(x) {
return tryMeAgain(x);//need to return the value returned by tryMeAgain to the caller of tryMe
};
//second named function
function tryMeAgain(y) {
return y;
};
//assign the result of first function to a var
var testTry = tryMe('worth a shot');
snippet.log(testTry);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
关于javascript 函数链中的变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31978870/