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

2022-08-07 16:53:51 +08:00
 DreamCMS
choose: function(obj) {
  obj.preview(function(index,file) {
    file.name; //获取到了文件名
  });
  this.data.key = file.name; //要获取给这个 data 里的 key ,但获取不到。
}
821 次点击
所在节点    问与答
6 条回复
DreamCMS
2022-08-07 16:57:10 +08:00
return 也出不来,显示未定义。
xiangyuecn
2022-08-07 17:19:43 +08:00
thisthisthisthisthisthisthisthisthisthisthisthisthisthisthis=this;
obj.preview(function(index,file) {
file.name; //获取到了文件名
thisthisthisthisthisthisthisthisthisthisthisthisthisthisthis.data.key = file.name;
});
reter
2022-08-07 17:25:42 +08:00
感觉是 X-Y 问题,同时没有完整的代码上下文。

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

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

感觉楼主没有理清楚执行逻辑
DreamCMS
2022-08-07 20:36:18 +08:00
@shintendo 确实是,逻辑上下执行先后没搞清楚。
Roojay
2022-08-07 20:36:56 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/871255

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX