How to refer to constructor methods when calling a function as an object property

时间:2016-10-20 19:33:31

标签: javascript node.js constructor prototype this

More questions about prototype inheritance, fun fun. I am making a Slack bot and am trying to keep my code neat and tidy. I have made a constructor for the bot to handle all needed methods and properties.

I was going to make an object on the prototype that held a bunch of functions related to a specific functional area (responding to chat commands). The problem is, I still need to refer to functions on the prototype from within these methods...I dunno how to do that:

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

and then from another function on the prototype:

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

So my question is....is there any neat way to put a bunch of functions in an object in order to use them, or do they all have to be directly on the prototype themselves? I tried putting them in the constructor, but same thing happened.

Thanks in advance.

2 个答案:

答案 0 :(得分:1)

You can remove the commands level by using Object.assign:

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

So, now you can write:

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

答案 1 :(得分:1)

Or you can do in this way

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

};

And call it

this.commands().tournament('message')