Smipto
20D
V2EX  ›  问与答

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

  •  
  •   Smipto · Aug 7, 2022 · 1686 views
    This topic created in 1554 days ago, the information mentioned may be changed or developed.
    choose: function(obj) {
      obj.preview(function(index,file) {
        file.name; //获取到了文件名
      });
      this.data.key = file.name; //要获取给这个 data 里的 key ,但获取不到。
    }
    
    6 replies  •  2022-08-07 20:36:56 +08:00
    Smipto
    Smipto
    OP
    Aug 7, 2022
    1
    return 也出不来,显示未定义。
    xiangyuecn
    xiangyuecn
    Aug 7, 2022❤️1
    2
    thisthisthisthisthisthisthisthisthisthisthisthisthisthisthis=this;
    obj.preview(function(index,file) {
    file.name; //获取到了文件名
    thisthisthisthisthisthisthisthisthisthisthisthisthisthisthis.data.key = file.name;
    });
    reter
    reter
    Aug 7, 2022❤️1
    3
    感觉是 X-Y 问题,同时没有完整的代码上下文。

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

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

    感觉楼主没有理清楚执行逻辑
    Smipto
    Smipto
    OP
    Aug 7, 2022
    5
    @shintendo 确实是,逻辑上下执行先后没搞清楚。
    Roojay
    Roojay
    Aug 7, 2022 via Android❤️1
    6
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1636 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 13:13 · PVG 21:13 · LAX 05:13 · JFK 08:13
    ♥ Do have faith in what you're doing.