【问题标题】:Chainable Object Methods可链接的对象方法
【发布时间】:2015-11-04 03:18:43
【问题描述】:

我对此有点迷茫。我知道我需要将它分配给另一个变量(例如:var that),以便方法可以链接。在不修改 modifyFunction 的情况下,我谁能使这个可链接? 如果你们中的任何人都可以解决这个问题,可以给我解释一下吗?

function modifyFunction(f) {
   console.log(f);
   return function() {
       var returnValue = f.apply(this, arguments);

       if (returnValue == undefined) {
           return this;
       } else {
           return returnValue;
       }
   };
}

function modifyMethod(o, m) {
   if (o.hasOwnProperty(m)) {
       console.log(o[m] instanceof Function);
       if (o[m] instanceof Function) {
           if (m == "add") {
               modifyFunction(this.o[m]);
           }
           console.log(this.o[m]);
           modifyFunction(o[m]);
           return this;
       }
   } else {
       return this
   }
}


var o = {
   num: 0,
   add: function(x) {
       return this.num += x;
   },
   sub: function(x) {
       return this.num -= x;
   }
};

// We can't chain object o's method because they don't return "this"
//o.add(4).sub(2); // fail - the methods aren't chainable yet!

// Make the add method chainable.
modifyMethod(o, "add");

// Now we can chain the add methods
o.add(2).add(4);
console.log(o.num); // o.num = 6

// Now make the sub method chainable
modifyMethod(o, "sub");

// Now we can chain both the sub and add methods
o.sub(1).add(3).sub(5);
console.log(o.num); // o.num = 3

【问题讨论】:

  • 只修改 modifyMethod 函数:)

标签: javascript object methods chain


【解决方案1】:

您可以在每个函数中将实例返回给整个 this 对象,以使其可链接:

var o = {
  num: 0,
  add: function(x) {
    this.num += x;
    return this;
  },
  sub: function(x) {
    this.num -= x;
    return this;
  },
  square: function() {
    this.num = this.num * this.num;
    return this;
  }
};

document.body.innerText = o.add(5).sub(2).add(4).square().num;

但是,您必须通过访问 .num 或调用像 value() 这样的特殊函数来提取最后一个值。

【讨论】:

  • 只是修改 modifyMethod.. 没有别的
  • @CodingBear15 原始问题包含“不修改 modifyFunction”。您是否只想通过编辑modifyFunction 使其工作?
  • 我的错,我的意思是说只修改 modifyMethod 函数。
猜你喜欢
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
  • 2019-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
  • 1970-01-01
相关资源
最近更新 更多