javascript - 帮我看下这个js小题,我已经阵亡了。。。
阿神
阿神 2017-04-11 12:56:21
[JavaScript讨论组]
var globalVal = test(hello, '!!!');

function hello(globalVal) {
    window.namee = globalVal;
    // 如何获取调用它的函数的返回值?
    console.log(globalVal);
}

function test(callback, val) {
    callback();
    console.log(val);
    return 'hello world'+val;
}

大家帮我看下这个我自己想的小题目,我是想在hello函数中获取调用它做为callback内部函数的返回值,我有点绕不清了,希望各位能提点好的解决方案,最好能指点下思路。谢谢了。

阿神
阿神

闭关修行中......

全部回复(10)
天蓬老师

你的意思是不是这样?

var globalVal = test(hello, '!!!');

function hello(globalVal){
    alert(globalVal); // hello world!!!
}

function test(callback, val) {
    var retVal = 'hello world' + val;
    callback(retVal);
    return retVal;
}

============== 所以题主是这个意思 (2016-09-23 09:36:05 更新) ==============

var globalVal = test(hello, '!!!');

function hello(){
    alert(globalVal); // hello world!!!
}

function test(callback, val) {
    setTimeout(callback);
    return 'hello world' + val;
}
天蓬老师

兄弟你这个做不到的啊。你执行hello函数完毕后,test的返回值还没有出来,你怎么能在hello中调用呢?你好像你在今天要知道你明天的想法,做不到的啊,你不能那一个在未来计算出来的值在之前函数中使用,明白了吗?

PHP中文网

我也被你绕进去了,你到底想干嘛?

伊谢尔伦
test(hello, '!!!');

function hello(globalVal) {
    window.namee = globalVal;
    // 如何获取调用它的函数的返回值?
    console.log(globalVal);
}

function test(callback, val) {
    console.log(val);
    //用回调函数传递
    callback('hello world'+val);
}
阿神

貌似要把值传给回调函数啊

怪我咯

undifine, hello world!!!

PHP中文网

完全没搞懂你想干什么,但是有点很清楚,test(hello, '!!!');这里调用hello没有传实参,也就是你hello函数里的代码都没有意义,你是想干嘛?

天蓬老师

不知道你想干嘛… 一脸懵X

PHP中文网

你test函数里的第一个参数 是 hello的值 但是他的返回值是undefined呀

阿神
var globalVal = test(hello, '!!!');

function hello(val) {
    console.log(val === globalVal)
}

function test(callback, val) {
    var rst = 'hello world'+val;
    callback(rst);
    return rst;
}

只能这样儿了,如果再调一次test给callback会形成死,循环的。当然,可以这样

function test(val, callback) {
    if (typeof callback === 'function'){
        callback(test(val));
    }
    return  'hello world'+val;
}

但是没有任何必要调用两次

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号