从webpack ES6作用域中的函数返回值

Returning value from a function in webpack ES6 - scope

本文关键字:函数 返回值 作用域 webpack ES6      更新时间:2023-09-26

我在webpack模块中返回一个值,但是我无法在函数外使用它。除非我犯了一个愚蠢的错误,否则我想也许我错过了一些关于模块工作方式的基本信息。谁能给我点化一下吗?

function getProjectID() {
  const project_id = document.getElementById('project-title')
                              .getAttribute('data-project-id');
  console.log("Project id inside is" + project_id); //Logs out the correct value
  return project_id;
}
getProjectID();
console.log("Project id outside is" + project_id); //Uncaught ReferenceError: project_id is not defined

JavaScript具有函数作用域,因此project_id不会在函数之外访问,因为这是它声明的地方。

指定返回值访问它:

const project_id = getProjectID();

根据你的代码和问题很难告诉你实际上想要返回什么,但我猜你想要一个模块,将从#project-title返回data-project-id属性的值。

如果我的假设是正确的,那么您实际上需要将module.exports设置为getProjectID函数。

getProjectId.js

module.exports = function getProjectID() {
    return document.getElementById('project-title').getAttribute('data-project-id');
}

注意:是否定义模块。exports函数是否为匿名并不重要,但为了清晰起见,我保留了名称。

someOtherFile.js

var getProjectId = require('getProjectId');
console.log('Project id is... %s', getProjectID());