如何在npm包函数中创建一个全局变量

时间:2017-06-29 23:17:09

标签: javascript node.js variables global-variables

我正在使用npm papercut https://www.npmjs.com/package/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) 




注销未定义

2 个答案:

答案 0 :(得分:1)

看起来像是一些异步代码。很可能在console.log()之前未调用回调,因此您的NewImg.input未定义。

同样var NewImg.input = Img在语法上不正确,请删除var

更新

详细了解异步javascript:Asynchronous 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) 

答案 1 :(得分:0)

如果在函数内使用var,则在函数内部使用相同的名称创建新变量。所以你的代码应该是:

var NewImg = {}

uploader.process('image1', file.path, function(images){
  var Img = images.avatar;
  NewImg.input = Img;
  console.log(Img);
  console.log(NewImg.input) 
})