gpt4 book ai didi

javascript - 如何将功能链接成一个句子

转载 作者:行者123 更新时间:2023-11-30 15:22:48 25 4
gpt4 key购买 nike

所以我必须编写一个程序,它可以像这样链接函数:name("Adam").place("cinema").movi​​e("xxx") 预期输出应该是这样的:Adam goes to Cinema to watch movie called xxx, what i so far:

    var test = function(name){

var self = {};
console.log(name)

function someFunc(where) {
console.log("goes to cinema" + where)
return self;
}

function someOtherFunc(what) {
console.log("to watch movie" + what)
return self;
}

self.someFunc = someFunc;
self.someOtherFunc = someOtherFunc;
return self;

}
console.log(test("Adam").someFunc("cinema").someOtherFunc("xxx"));

但它给了我不同行的字符串,我想用一句话来表达,任何帮助将不胜感激。

最佳答案

你可以这样做:

var test = function(message) {

this.someFunc = function(where) {
message += ` goes to ${where}`;
return this; // Allow chaining
}

this.someOtherFunc = function(what) {
message += ` to watch movie ${what}`;
return this; // Allow chaining
}

this.value = function() {
return message; //End chain
}

return this; // Start chain

}
console.log(test("Adam").someFunc("cinema").someOtherFunc("xxx").value());
//Adam goes to cinema to watch movie xxx


编辑:

是否可以在没有 .value() 的情况下获得该结果?

您可以覆盖 .toString()

Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object, toString() returns "[object type]", where type is the object type.

虽然这需要将对象转换为字符串。

var test = function(message) {

this.someFunc = function(where) {
message += ` goes to ${where}`;
return this;
}

this.someOtherFunc = function(what) {
message += ` to watch movie ${what}`;
return this;
}

this.toString = function() {
return message;
}

return this;

}

console.log(`${ test("Adam").someFunc("cinema").someOtherFunc("xxx")}`);

关于javascript - 如何将功能链接成一个句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43440822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com