V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
DreamCMS
V2EX  ›  问与答

[求解] 如何把 function 里的变量赋值给外部某个变量上来

  •  
  •   DreamCMS · 2022-08-07 16:53:51 +08:00 · 815 次点击
    这是一个创建于 617 天前的主题,其中的信息可能已经有所发展或是发生改变。
    choose: function(obj) {
      obj.preview(function(index,file) {
        file.name; //获取到了文件名
      });
      this.data.key = file.name; //要获取给这个 data 里的 key ,但获取不到。
    }
    
    6 条回复    2022-08-07 20:36:56 +08:00
    DreamCMS
        1
    DreamCMS  
    OP
       2022-08-07 16:57:10 +08:00
    return 也出不来,显示未定义。
    xiangyuecn
        2
    xiangyuecn  
       2022-08-07 17:19:43 +08:00   ❤️ 1
    thisthisthisthisthisthisthisthisthisthisthisthisthisthisthis=this;
    obj.preview(function(index,file) {
    file.name; //获取到了文件名
    thisthisthisthisthisthisthisthisthisthisthisthisthisthisthis.data.key = file.name;
    });
    reter
        3
    reter  
       2022-08-07 17:25:42 +08:00   ❤️ 1
    感觉是 X-Y 问题,同时没有完整的代码上下文。

    我推测你遇到的问题是:在 preview 的回调函数无法指向你期待的 this 对象。
    原因:function 内的 this 会根据执行的上下文发生变化
    解决方法:
    1. 用箭头函数,让 this 指向声明时的 this
    2. 用 bind() 显式绑定 this
    shintendo
        4
    shintendo  
       2022-08-07 17:59:00 +08:00   ❤️ 1
    为啥你们觉得是 this 的问题,这不是作用域的问题吗,file 是匿名回调函数的局部变量,外面肯定取不到呀

    另外也不知道你这回调函数是同步的异步的,异步那就是另外的问题了

    感觉楼主没有理清楚执行逻辑
    DreamCMS
        5
    DreamCMS  
    OP
       2022-08-07 20:36:18 +08:00
    @shintendo 确实是,逻辑上下执行先后没搞清楚。
    Roojay
        6
    Roojay  
       2022-08-07 20:36:56 +08:00 via Android   ❤️ 1
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4035 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 05:11 · PVG 13:11 · LAX 22:11 · JFK 01:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.