作为对象属性调用函数时如何引用构造函数方法

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

本文关键字:引用 方法 构造函数 何引用 对象 属性 调用 函数      更新时间:2023-09-26

更多关于原型继承的问题,有趣有趣。我正在做一个Slack机器人,我试图保持我的代码整洁。我已经为机器人做了一个构造函数来处理所有需要的方法和属性。

我打算在原型上创建一个对象,该对象包含与特定功能区域相关的一系列功能(响应聊天命令)。问题是,我仍然需要从这些方法中引用原型上的函数……我不知道该怎么做:

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

我的问题是....是否有一种简洁的方法可以将一堆函数放在对象中以便使用它们,或者它们都必须直接在原型本身上?我试着把它们放在构造函数中,但同样的事情发生了。

或者你可以这样做

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

};

命名为

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

您可以使用Object.assign:

删除commands级别。
// 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
  }
}

那么,现在你可以写:

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