【问题标题】:Using Javascript object in seperate file在单独的文件中使用 Javascript 对象
【发布时间】:2020-05-17 22:43:17
【问题描述】:

我正在使用 Nativescript-vue。我试图在我的应用程序中添加一些逻辑,它不显示任何 html 或任何内容,它只是一个进行计算的库。我不知道如何使用它,我不断收到错误消息。

这是我尝试过的。

步枪.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

【问题讨论】:

  • 我从未使用过 vue,但我希望导出的 Rifle 值是一个函数或一个类。这表明您需要先创建该类的实例,然后再使用它。另外,我认为您无法使用“this”访问导入的类。你可以试试 。常量步枪=新步枪(); this.msg = 步枪.firstName;
  • @RainerPlumer 这成功了,export function Rifle () { // 没有函数名 this.firstName="hi"; function GetHelp (){ return "Help" } } 你知道为什么我的函数 GetHelp 不起作用吗?

标签: javascript nativescript nativescript-vue


【解决方案1】:
  • 将评论移到答案中以更好地格式化 *

我从未使用过 vue,但我希望导出的 Rifle 值是一个函数或一个类。这表明您需要先创建该类的实例,然后再使用它。 另外,我认为您无法使用“this”访问导入的类。你可以试试。

// 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

【讨论】:

  • 非常感谢。我一直在努力让它像这样工作一段时间,并且做到了。
【解决方案2】:

这里的问题是this.firstName。阅读this以更好地了解如何在js中使用this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 2017-12-11
    • 2014-06-07
    相关资源
    最近更新 更多