2017-07-20 12 views
0

私は今nodejsを学んだし、Imはどのように思って、私は、例えば、他のファイルNodejs他のファイルからクラスオブジェクトへの参照

で作成したオブジェクトに参照することができます。 私は私のクラスユーザーとファイルを持っています。私は

module.exports = class Username { 

    constructor(name, lastProjects) { 
    this.current.name = name; 
    this.current.lastProjects = lastProjects; 
    } 

}; 

name.handler.jsを輸出していますJS私はそれ、これはファイル

const Alexa = require('alexa-sdk'); 
const User = require('../models/user.model'); 
module.exports = Alexa.CreateStateHandler(StatesConst.NAME, { 
    'NewSession': function() { 
    this.emit('NewSession'); // Uses the handler in newSessionHandlers 
    }, 
    'MyNameIsIntent': function() { 
    var user = new User.Username("Anna", ["project1", "project2"]); 
    this.emit(':ask', "Hi "+User.Username.name); 
    } 
    } 
をオーデルにエクスポートすることはできません

user.handler.js私はtottaly私は私のprogramm内の他のファイルに新しいユーザーオブジェクトに参照することができますどのように私の新しい作成されたオブジェクトのユーザー名

const Alexa = require('alexa-sdk'); 
const User = require('../models/user.model'); 
module.exports = Alexa.CreateStateHandler(StatesConst.NEWSTATE, { 
    'NewSession': function() { 
    this.emit('NewSession'); // Uses the handler in newSessionHandlers 
    }, 
    'MyUserIntent': function() { 
    this.emit(':ask', "My username is "+User.Username.name); 
    } 
    } 

への参照を書くことができる方法を知っていけませんか?私はユーザーがプログラムを開始するたびに新しいユーザーオブジェクトを取得し、他のすべてのファイルの属性を参照および変更できるようにしたいと思います。私は非常に助け:)メッセージ=を取得する場合

+0

、文はrequire('../models/user')ようになるはずではない必要がCannot read property 'name' of undefined

を得るのだろうか? – error404

答えて

0
module.exports = Username; 




const Alexa = require('alexa-sdk'); // ok? 
const User = // in linux, to go 1 dir up is just '.' 
console.log(require('../models/user.model')) 

が見るために感謝することでしょう。「[機能:ユーザー名]」」

あなたはあなたに何かを伝えるメッセージが表示されますない場合はたぶんありません。見つかったファイルあなたがmodule.exportsに割り当てることによってUsernameを輸出しているので、あなたのハンドラ内new Userとしてそれを使用する必要が

0

例えば、name.handler.jsになるでしょう:。。

const Alexa = require('alexa-sdk'); 
const User = require('../models/user.model'); 
module.exports = Alexa.CreateStateHandler(StatesConst.NAME, { 
    'NewSession': function() { 
     this.emit('NewSession'); // Uses the handler in newSessionHandlers 
    }, 
    'MyNameIsIntent': function() { 
     var user = new User("Anna", ["project1", "project2"]); 
     this.emit(':ask', "Hi "+user.name); 
    } 
} 

this.emit行では、クラス自体ではなく、Userのインスタンスを使用する必要があります。 (したがってUserの代わりにuser)。

さらに、のuser.handler.jsファイルでは、Userをインスタンス化しません。あなたのUsernameクラスがuser.jsのであれば最後に、あなたはあなたがどのようにエクスポートとインポートクラスとそれを使用することを意味しませんrequire('../models/user-model')

+0

ありがとうございました:)本当にuser.handler.jsに値user.nameを取得することはできませんか?私は、ファイルname.handler.jsに定義されている値を取得したいと思います。 –

+0

** user.handler.js **の 'name'にアクセスするには、** nameにそれを公開する方法を見つける必要があります.handler.js **:その属性にアクセスするには 'User'のインスタンスが必要です。私は 'alexa-sdk'パッケージに精通していませんが、ハンドラ間で状態/属性を共有できないようです。それらをマージする必要があるかもしれません。あなたは彼らの例を見て、これがあなたを助けるかもしれないかどうかを見てみましょうか? [スキルの状態管理を簡単にする](https://www.npmjs.com/package/alexa-sdk#making-skill-state-management-simpler) – yazgazan

関連する問題