2016-10-20 8 views
0

プロトタイプの継承、楽しい楽しみに関するその他の質問。私はスラックボットを作っていて、自分のコードをすっきりと整えておくよう努めています。私は必要なメソッドとプロパティをすべて処理するためのボットのコンストラクタを作成しました。オブジェクトプロパティとして関数を呼び出すときのコンストラクタメソッドの参照方法

私は、特定の機能領域に関連する一連の機能(チャットコマンドに応答する)を保持するプロトタイプ上にオブジェクトを作成しようとしていました。プロトタイプ上の別の関数から、その後

// generic function I put on prototype 
SmashBot.prototype.postMessage = function() { 
    'do stuff' 
} 

// helper object full of functions I need 
SmashBot.prototype.commands = { 

    tournament: function(message) { 
    this.postMessage('stuff');  // Method on SmashBot Prototype i need to use 
    console.log(this)  // refers to this object (Smashbot.commands) 
    }, 

    self: (message) => { 
    this.createTourney('stuff') // another method on prototype 
    console.log(this); // lexical arrow function makes 'this' just refer to '{}', not the constructor 
    } 
} 

と::問題は、私はまだ私はそれを行う方法を知らない...これらの方法の中から、プロトタイプで関数を参照する必要があり、ある

this.commands.tournament() 
     // <--- this.postMessage() is not a function 

だから私の質問は....それらを使用するために、オブジェクトの機能の束を置くために任意のきちんとした方法はありますか、それらはすべてプロトタイプ自体に直接する必要がありますか?私はそれらをコンストラクタに入れようとしましたが、同じことが起こりました。

ありがとうございます。

var obj = new Smashbot(); 
obj.tournament('test'); 
+1

'this.commands.tournament.apply(これは)'働く –

+0

@Maximusを動作するはず呼んで!しかし、関数にパラメータを渡す方法はありますか?編集しないでください、私はそれを見つけました。この値の後にちょうどパスしてくださいありがとう! – joh04667

+1

'call'で引数を渡すこともできます:' this.commands.tournament.call(this、 'message') ' – trincot

答えて

1

それとも、この方法

SmashBot.prototype.commands = function(){ 
let self = this; 
return { 
    tournament: function (message) { 
     self.postMessage('stuff');  // Method on SmashBot Prototype i need to use 
     console.log(this)  // refers to this object (Smashbot.commands) 
    }, 
    self: (message) => { 
     self.createTourney('stuff') // another method on prototype 
     console.log(this); // lexical arrow function makes 'this' just refer to '{}', not the constructor 
    } 
} 

}で行うことができます。

だから、
// helper object full of functions I need 
Object.assign(SmashBot.prototype, { 

    tournament: function(message) { 
    this.postMessage('stuff');  // Method on SmashBot Prototype i need to use 
    console.log(this)  // refers to this object (Smashbot.commands) 
    }, 

    self: (message) => { 
    this.createTourney('stuff') // another method on prototype 
    console.log(this); // lexical arrow function makes 'this' just refer to '{}', not the constructor 
    } 
} 

は、今あなたが書くことができます。

+0

ああ、それは素晴らしい考えです。ありがとう! – joh04667

1

あなたはObject.assignを使用してcommandsレベルを削除することができます;

そして、それは

this.commands().tournament('message') 
関連する問題