在 JavaScript 中使对象方法可链接

Make an objects methods chainable in JavaScript

我一直在与这个项目作斗争并理解这个概念,但无法全神贯注于如何获得最终结果。

鉴于此代码:

<!doctype html>
<html>
<head>
  <title> Make an objects methods chainable </title>
  <meta charset="utf-8">
  <script>

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

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

   function modifyMethod(o, m) {
   // your code here
   //the object being passed is the var o
  //the method being passed is the add or sub functions contained in the
  // var

  var methodIn = o[m]; 
  var objectIn = o;
  var numIn;

  console.log("Method In: " + methodIn);
  console.log("Object In: " + objectIn);

    if (o.hasOwnProperty(m) ) { 
     var property = o[m];   
     console.log(property);
     console.log("o has property " + m); 
     modifyFunction(this);

     if (methodIn instanceof Function) {
     //  if (this instanceof o) {

       modifyFunction(o);
       return this;
       console.log("This after modifyFunction: " + this);
       console.log("after modifyFunction " + this);

     }        
        modifyFunction(m);   
      } 

 if (!o.hasOwnProperty(m)) {
    console.log("Function not contained in Object");
 }


}  

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

 // We cannot chain object o(s) method because they do not return 
 //--this--
 //o.add(4).sub(2); // fail - the methods are not 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
 </script>
</head>
<body>
</body>
</html>

objective是通过hasOwnProperty和instanceof来判断传入的对象是否有传入的方法属性,这个我理解,在控制台也能看到结果。 instanceof 应该检查对象的 属性 是否是函数的实例,我对此不太清楚并不断收到返回的错误消息(预期的函数)。如果我理解正确,我需要将信息传递到 modifyFunction 以执行计算吗?

我看到对象被传递到函数和方法(添加和子)函数中,但就是想不通我需要做什么才能让它工作。对于此代码,我提前表示歉意,但有人可以帮助我了解如何将 "this" 全部绑定在一起吗?

我已经浏览了关于这个主题的所有帖子,但仍然无法理解。 谢谢!

函数可以像 JavaScript 中的变量一样传递,但它们本质上是不可变的,就像字符串一样。如果我给你这个代码:

a = "my string";
b = a;

...然后要求您将 a 更改为 "your string",但没有任何 a = 块(因此,更改实际的 "my string" 对象,而不是参考),然后除非采取一些可能极端的 JS 黑客措施,否则你无法做到这一点。它们被创建并保持不变 - 但通常有方法从现有的创建类似的。

同样,由于您不能 "change" 一个函数,modifyFunction 并没有像您想象的那样做,因为您没有将其调用的结果分配给任何东西。因此,在某些方面,我批评的是术语差异 - 你不能 "modify" 一个函数,但是,你可以将其本地引用替换为引用原始文件并执行你喜欢的操作的引用。尝试替换这部分代码;您可以删除 modifyFunction

的另一个实例
if (methodIn instanceof Function) {
 //  if (this instanceof o) {

   o[m] = modifyFunction(m);
   return o;

}

我最近注意到的另一个问题是您将对象传递给 modifyFunction,而不是方法。此外,未以正确的方式调用您的函数以使用 this 关键字。它是从全局上下文中调用的,因此 this 可能只是 window。只需将对 this 的任何其他必要引用更改为 o,就可以了。