是否可以在不创建新对象的情况下链接Javascript函数?

问题描述 投票:1回答:1

想象我们有一个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:出于学习目的,我试图链接功能,但对它的理解不足以理解上述行为。将其返回到普通函数中以将其他函数链接到该函数也不会执行此操作。最后我想将一个函数的结果“传递”到另一个函数

javascript ecmascript-6 fluent chaining
1个回答
2
投票

尽管不容易看到,但这里的问题是命名!

您正在创建一个名为property的原型函数,然后实质上是使用从函数调用中获得的值覆盖此函数。检查下面代码中的注释。

FStyle.prototype.property = function(property) {
  // at this point "ourButtonStyle.property" is a function
  this.property = property;
  // here "ourButtonStyle.property" is a string 
  return this;
}

一个简单的解决方法是使用稍微不同的名称来重命名这些名称>

var FStyle = function(node) {
  this.node = node;
}

FStyle.prototype.property = function(prop) {
  this.prop = prop;
  return this;
}

FStyle.prototype.value = function(val) {
  this.val = val;
  this.node.style[this.prop] = this.val;
  return this;
}
    
© www.soinside.com 2019 - 2024. All rights reserved.