首页 > 解决方案 > 无限函数调用,例如 '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 只能调用一次。对话也是可选的,在这种情况下,如果没有对话,则对话对象不应出现在输出中。

标签: javascript

解决方案


要创建自定义结构化对象,请使用构造函数,例如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 来避免列出继承的方法)


推荐阅读