作为对象属性调用函数时如何引用构造函数方法
How to refer to constructor methods when calling a function as an object property
更多关于原型继承的问题,有趣有趣。我正在做一个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');
相关文章:
- 引用类变量中的原型方法
- 有没有一种方法可以通过只引用JavaScript来执行代码
- 可以“;超级“;可以在子类的方法内部使用,在不直接引用的情况下调用相应的超类方法
- 通过引用Javascript中的另一个函数来传递对象方法
- 这在 Object 方法中不引用对象,而是引用函数绑定到的标记
- 在方法中失去对对象的引用
- 使用clearInterval方法实现的是将区间变量引用设置为null,而不是
- 有没有一种方法可以捕获JavaScript控制台输出,以便我可以在其他地方引用它
- 有没有一种方法可以重新绑定jQuery插件中引用的事件处理程序
- 在JQuery中,'加载'方法'的相对路径在引用项目中的html文件时开始
- 可以't从客户端应用程序引用插件中定义的静态方法
- 更好的设计,以便从对象的方法引用自己的对象的属性
- 为什么Javascript库对数组方法(push,slice等)有本地引用
- 模仿通过引用而不是值将数字传递给函数的任何方法
- 从充当事件处理程序的多个方法引用对象属性
- 在 javascript 中将“this”引用传递给方法的提示
- Java Nashorn中的(De)引用方法变体
- 在 JavaScript 中,如何从更深层次的嵌套方法引用方法的返回值
- 如何从对象中引用方法
- 在init之前引用方法