JS String传值后离开作用域被赋值的对象变成空字符串,问题出在哪里?

如题,我使用了Electron的截图方法,在data()函数中定义了一个picPath用来保存截图的目标路径(通过_self.picPath访问)。截图成功后我用picPath存放forEach函数中的截图路径(只有一个所以直接用了字符串存放)。但是比较神奇的是离开sources.forEach函数后,_self.picPath也变成空的字符串了。

在网上查找资料得知,JS中String属于基本数据类型,互相赋值时为值传递,那为什么还会产生上述情况?

mounted() {
    require('electron').ipcRenderer.on('synchronous-reply', (event, message) => {
      if (message.content === 'capture') {
        const electron = require('electron')
        const desktopCapturer = electron.desktopCapturer
        const fs = require('fs')
        const path = require('path')
        var options = { types: ['screen'], thumbnailSize: message.param }

        desktopCapturer.getSources(options, function (error, sources) {
          if (error) {
            console.log(error)
          }
          sources.forEach(function (source) {
            var fileName = (new Date()).valueOf() + '.png'
            const screenshotPath = path.join(_self.form.dir, 'Game', 'Screenshots', fileName)
            fs.writeFile(screenshotPath, source.thumbnail.toPNG(), function (error) {
              if (error) {
                console.log(error)
              }
            })
            _self.picPath = screenshotPath
            console.log(_self.picPath) // 打印正常路径
          })
        })

        console.log(_self.picPath) // 打印 ''
      }
    })
}
阅读 2.2k
2 个回答

desktopCapturer.getSources返回Promise<DesktopCapturerSource[]>,异步的,
回调函数外面的console.log(_self.picPath) 拿不到结果

不是很了解electron,但是说一下我的猜测,desktopCapturer里的函数应该是异步的,所以之所以打印''是因为根本还没被赋值呢

        desktopCapturer.getSources(options, function (error, sources) {
           // 这个后执行 
           console.log(_self.picPath) 
           // 打印正常路径
          
        })
        // 这个先执行 
        console.log(_self.picPath) // 打印 ''
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题