javascript - 在另一个文件中获取变量
问题描述
是否可以从另一个文件访问另一个变量?
例如firstFile
:
export default class myClass {
constructor({name, price}) {
this.name = name;
this.price = price;
}
}
在一个单独的文件中,我正在做:
new VendingMachineItem({ name: "Cheese Puffs", price: 3 }),
new VendingMachineItem({ name: "Can of Soda", price: 1.75 })
这样它现在就可以在我要访问的另一个文件中运行构造函数,this.price
并且this.name
.
我目前正在将其导入此文件中,但不确定该怎么做...
解决方案
An imported class behaves like you've defined the class right in the file, where you use it.
So, this:
class Foo{ /*...*/ }
new Foo()
is equivalent to this:
//foo.js
export default class Foo{ /*...*/ }
//bar.js
import Foo from './foo.js'
new Foo()
So, use your class normally after you've imported it.
The this
inside the class constructor refers to the newly created object.
So, you define name
and price
on the object, that got returned from the constructor!
Therefore just use the return value of the constructor:
const newObject = new VendingMachineItem({ name: "Cheese Puffs", price: 3 })
console.log(newObject.name) //Cheese Puffs
console.log(newObject.price) //3
推荐阅读
- ios - iOS 通知附件图像的完美(或最大)分辨率是多少?
- java - 如何从 Aqua 表自动生成界面?
- c - 指向包含指向包含结构的指针的结构的嵌套指针?
- node.js - 使用 Twilio 从客户端到服务器的 SMS
- c# - c#windows服务:错误1053
- python - 从两个不同的目录导入两个 python 模块
- groovy - CrafterCMS:如何输出由 solr 索引的 html 正文?
- react-native - react-transform-hmr/lib/index.js could not be found
- php - 删除前一个会话后如何创建新会话?
- java - 不要更改鼠标悬停检票口上的文本颜色