首页 > 解决方案 > 在另一个文件中获取变量

问题描述

是否可以从另一个文件访问另一个变量?
例如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.

我目前正在将其导入此文件中,但不确定该怎么做...

标签: javascriptes6-moduleses6-class

解决方案


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

推荐阅读