【发布时间】:2021-03-28 01:57:33
【问题描述】:
我想使用其他 js 文件中的变量,但是当我使用不起作用的导入和导出语句时,因为没有定义 {file}。 我的问题是我的变量在一个函数中,并且在一个循环中。 我想我做错了,但你能帮帮我吗?
这是我的 fabric.js 上的代码
const initCanvas = () => (
new fabric.Canvas('canvas', {
preserveObjectStacking:true,
height: 450,
width: 600,
backgroundImage: {file}, <--- i want to use the variable "file" here
})
)
在我的 emil.js 中,我有一个带有此代码的函数
DisplayCategory(category) {
(...) //Function that generate te list of
else { //Generate the product list of a category (ex : product[2][x])
let product = [];
let x = findProduct(product_array, selected_product);
for (let y = 1; product_array[x][y]; y++) {
var ext = ".jpg";
var file = '/' + product_array[x][y] + ext; <--- file is defined here
product.push(
<Card style={{ width: '18rem' }} className={this.takeClass(product_array[x][y])} onClick={() => this.HandleOnClick(product_array[x][y], 2)}>
<Card.Img variant="top" src={file} /> <--- and is used here
函数太长了,剩下的就不放了
【问题讨论】:
-
你不能——至少不能这样。变量在声明它们的范围内是本地的。如果它们到处泄漏到全局范围内,所有的地狱都会崩溃。您说您在导入/导出方面遇到问题,但没有表明这一点。我会将其作为一个单独的问题发布,并详细说明您面临的问题。
-
好的,谢谢,如果我在顶层定义了“ext”和“file”并且我使用了“this”?可以吗?
-
如果您的脚本共享一个公共命名空间(在
window上声明的对象),那么,是的,它们可以通过这种方式共享数据。有一个全局命名空间是很常见的,比如window上的myProject,这是你在全局范围内编写的唯一内容,并且一切都存在于其中。 -
好的,谢谢您的回答。我不知道如何解决我的问题,但我继续搜索^^
-
查看答案.....