[英]How to make a global variable within a npm package function
我正在使用npm papercut https://www.npmjs.com/package/papercut ,我想訪問papercut函數中的變量值。 到目前為止,這就是我所擁有的。
我想在函數外部訪問變量Img的值,這里的變量NewImg我試圖使用全局變量來實現。 任何人看到我的問題或有任何建議。
var NewImg = {} uploader.process('image1', file.path, function(images){ var Img = images.avatar NewImg.input = Img console.log(Img); }) console.log(NewImg.input)
這注銷未定義
看起來像一些異步代碼。 可能未在console.log()
之前調用回調,因此您的NewImg.input
是未定義的。
同樣, var NewImg.input = Img
在語法上不正確,請刪除var
。
閱讀有關異步javascript的更多信息: 異步Javascript
var NewImg = {}
uploader.process('image1', file.path, function(images){
// I'm a callback function in an asynchronous method!
// I will run sometime in the future!
var Img = images.avatar
NewImg.input = Img
console.log(Img);
})
// Oh no! I ran before the callback function in the *asynchronous* method above, before NewImg.input is assigned any value
console.log(NewImg.input)
如果在函數內部使用var
,則在函數內部使用相同的名稱創建新變量。 因此,您的代碼應為:
var NewImg = {}
uploader.process('image1', file.path, function(images){
var Img = images.avatar;
NewImg.input = Img;
console.log(Img);
console.log(NewImg.input)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.