- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我必须编写一个程序,它可以像这样链接函数:name("Adam").place("cinema").movie("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/
我是一名优秀的程序员,十分优秀!