javascript - 无限函数调用,例如 'string'.replace().replace()
问题描述
我不确定如何解释,所以我将从输出开始。我需要返回这个:
{
replies:
[
{ type: 'text', content: 'one' }
{ type: 'text', content: 'two' }
{ type: 'text', content: 'three' }
],
conversation: {
memory
}
}
我想通过内联语句返回它。所以我想这样称呼:
reply.addText('one').addText('two').addText('three').addConversation(memory)
请注意,addText 可以无限次调用,而 addConversation 只能调用一次。对话也是可选的,在这种情况下,如果没有对话,则对话对象不应出现在输出中。
解决方案
要创建自定义结构化对象,请使用构造函数,例如Reply
.
要在方法调用的返回值上调用实例方法,请从方法中返回实例对象。
防止多次添加对话对象的选择包括抛出错误(如下所示)或可能记录警告,并且在第一次调用addConversation
.
编写代码来实现需求。
例如使用香草 javascript:
function Reply() {
this.replies = [];
}
Reply.prototype.addText = function( content) {
this.replies.push( {type: "text", content: content});
return this;
}
Reply.prototype.addConversation = function( value) {
if( this.conversation) {
//throw new Error("Only one conversation allowed");
}
this.conversation = {conversation: value};
return this;
};
Reply.prototype.conversation = null;
// demo
var reply = new Reply();
reply.addText( "one").addText("two").addConversation("memory?");
console.log( JSON.stringify( reply, undefined," "));
(console.log 使用 JSON stringify 来避免列出继承的方法)
推荐阅读
- r - 选择另一个表中存在单词的行
- node.js - 从我的 MEAN 应用程序上传的图像有时不显示
- excel - 如何获取 Google 表单下拉列表的唯一 ID?
- r - 用能量填充每日负载曲线以填充低谷
- java - 基于java 8中的同名条件将所有hashmap放在一起
- python - Selenium 单击instagram Python上的所有关注按钮
- python - python正则表达式正则表达式
- r - 将某些列重新调整为 R 中的特定平均值和标准差
- vbscript - 以 // 开头的 asp 经典 vBscript 行
- dictionary - 如何让 SwiftUI 检测字典的更改?