我具有此功能并且工作正常:
const playlistPath = path.join(config.PLAYLIST_PATH, this.playlist.id + '.json')
let playlistString = JSON.stringify(this.playlist)
mkdirp(config.PLAYLIST_PATH, function (_) {
fs.writeFile(playlistPath, playlistString, function (err) {
if (err) return console.log('error saving album to playlist %s: %o', playlistPath, err)
console.log('The album has been added to the playlist');
})
})
但是如果我要删除var playlistString
并直接使用JSON.stringify
则无法正常工作,则该文件将使用未定义的格式写入。
const playlistPath = path.join(config.PLAYLIST_PATH, this.playlist.id + '.json')
mkdirp(config.PLAYLIST_PATH, function (_) {
fs.writeFile(playlistPath, JSON.stringify(this.playlist), function (err) {
if (err) return console.log('error saving album to playlist %s: %o', playlistPath, err)
console.log('The album has been added to the playlist');
})
})
为什么?
答案 0 :(得分:2)
该问题是由this的作用域引起的。在编写this.playlist
的第二个代码块中,它引用调用函数。在这种情况下,您的回调function (err)...
拥有this
。
要解决此问题,请将this
分配给一个变量,然后使用该变量引用您想要的上下文。
const playlistPath = path.join(config.PLAYLIST_PATH, this.playlist.id + '.json');
// Hold the value of "this" in a variable "ref"
const ref = this;
mkdirp(config.PLAYLIST_PATH, function (_) {
fs.writeFile(playlistPath, JSON.stringify(ref.playlist), function (err) {
if (err) return console.log('error saving album to playlist %s: %o', playlistPath, err)
console.log('The album has been added to the playlist');
})
})