有没有办法在不创建新对象的情况下链接Javascript函数?

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

iCMS 回答:有没有办法在不创建新对象的情况下链接Javascript函数?

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

您正在创建一个名为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;
}
本文链接:https://www.f2er.com/2234348.html

大家都在问