想象我们有一个Button元素
const ourButton = document.getElementById("#theButton");
我们希望使用流畅的API来更改此按钮的样式而无需创建新对象,因此可以像这样链接函数:
style(ourButton).property("padding").value("32px");
这可能吗?我似乎无法弄清楚如何创建这种行为。我尝试通过创建如下构造函数来构建Fluent API“常规方式”:
var FStyle = function(node) {
this.node = node;
}
FStyle.prototype.property = function(property) {
this.property = property;
return this;
}
FStyle.prototype.value = function(value) {
this.value = value;
this.node.style[this.property] = this.value;
return this;
}
并通过构造新对象来使用它:
const ourButtonStyle = new FStyle(ourButton);
ourButtonStyle.property("padding").value("64px");
哪个工作一次。如果要添加新样式,则必须创建一个全新的对象。为什么会这样?
TL; DR:出于学习目的,我试图对功能进行链接,但对它的理解还不够全面,无法理解上述行为。将其返回到普通函数中以将其他函数链接到该函数也不会执行此操作。最后,我想将一个函数的结果“传递”到另一个函数。