在单独的文件中使用 Javascript 对象
Using Javascript object in seperate file
我正在使用 Nativescript-vue。我试图在我的应用程序中加入一些逻辑,它不显示任何 html 或任何东西,它只是一个进行计算的库。我不知道如何使用它,我不断收到错误消息。
这是我试过的方法。
rifle.js
export function Rifle () { // no function name
this.firstName = "hi";
}
也试过这个和其他的:
const observableModule = require("tns-core-modules/data/observable");
function Rifle () { // no function name
const myRifle = observableModule.fromObject({
firstName:"hello"
})
return myRifle;
}
module.exports = Rifle;
然后在我的 App.js 文件中导入它。
import {Rifle} from "./ballisticlibrary/rifle";
我也尝试过使用 Require。
然后我尝试在 vue 方法中使用它,在点击按钮时调用。
GetRifle()
{
// return "hi";
this.msg= this.Rifle.firstName;
}
不断抛出错误:
Cannot read property 'firstName' of undefined"
System.err: An uncaught Exception occurred on "main" thread.
System.err: Calling js method onClick failed
System.err: TypeError: Cannot read property 'firstName' of undefined
这里的问题是this.firstName
。阅读 this 以更好地理解如何在 js.
中使用 this
- 将评论移到答案中以获得更好的格式 *
我从未使用过 vue,但我希望导出的 Rifle 值是一个函数或 class。这表明您需要先创建 class 的实例,然后再使用它。
另外,我认为您无法使用 "this" 访问导入的 classes。你可以试试。
// your rifle class
export function Rifle () {
this.name = "AK-47";
this.damage = 5;
this.fire = () => {
console.log('Bang bang, '+ this.damage + ' damage done by ' + this.name);
}
}
// then import your rifle and instantiate it
const ak = new Rifle();
ak.fire();
// logs out Bang bang, 5 damage done by AK-47
我正在使用 Nativescript-vue。我试图在我的应用程序中加入一些逻辑,它不显示任何 html 或任何东西,它只是一个进行计算的库。我不知道如何使用它,我不断收到错误消息。
这是我试过的方法。
rifle.js
export function Rifle () { // no function name
this.firstName = "hi";
}
也试过这个和其他的:
const observableModule = require("tns-core-modules/data/observable");
function Rifle () { // no function name
const myRifle = observableModule.fromObject({
firstName:"hello"
})
return myRifle;
}
module.exports = Rifle;
然后在我的 App.js 文件中导入它。
import {Rifle} from "./ballisticlibrary/rifle";
我也尝试过使用 Require。
然后我尝试在 vue 方法中使用它,在点击按钮时调用。
GetRifle()
{
// return "hi";
this.msg= this.Rifle.firstName;
}
不断抛出错误:
Cannot read property 'firstName' of undefined"
System.err: An uncaught Exception occurred on "main" thread.
System.err: Calling js method onClick failed
System.err: TypeError: Cannot read property 'firstName' of undefined
这里的问题是this.firstName
。阅读 this 以更好地理解如何在 js.
this
- 将评论移到答案中以获得更好的格式 *
我从未使用过 vue,但我希望导出的 Rifle 值是一个函数或 class。这表明您需要先创建 class 的实例,然后再使用它。 另外,我认为您无法使用 "this" 访问导入的 classes。你可以试试。
// your rifle class
export function Rifle () {
this.name = "AK-47";
this.damage = 5;
this.fire = () => {
console.log('Bang bang, '+ this.damage + ' damage done by ' + this.name);
}
}
// then import your rifle and instantiate it
const ak = new Rifle();
ak.fire();
// logs out Bang bang, 5 damage done by AK-47