如何在JavaScript中检测方法链的结束? [英] How to detect the end of a method chain in JavaScript?
问题描述
首先,最重要的是,我正在尝试检测方法链的结束调用。我还想设法一种方法来检测方法链中方法调用中对象链中或向下有多少方法。
Firstly and most importantly I'm trying to detect the end call of a method chain. I would also like to devise a way to detect how many methods "in" or "down" an object chain I am within my method calls in a method chain.
For例如,在我写的插件中:
For instance, in the plugin I'm writing:
var result = $("#someDiv").myPlugin.foo().bar()._foo()._bar();
假设方法当前正在执行.bar()我想知道我是2链接中的方法。
Say the method is currently executing in .bar() I would like to know that I'm 2 methods down the chain.
我需要以某种方式抽象这些信息的原因是当我到达链中的最后一个方法时我可以返回结果而不是插件对象因此打破了链接,以便在'result'变量中获取对我们数据的访问权。
The reason I need to abstract this information in some manner is so when I reach the last method in the chain I can return a result instead of the plugin object thus breaking the chain at that point for the sake of gaining access to our data in the 'result' variable.
推荐答案
以下是来自您的项目的示例:
var strLenA = parseInt( P.strlen('some string').data );
var strLenB = parseInt( P.strlen('another string').data );
var totalStrLen = strLenA + strLenB;
console.log(strLenA, strLenB, totalStrLen);
从这里我可以看出为什么我们的答案不够实际 - 以及为什么你想要摆脱 .data
。令人高兴的是,无论如何, .data
总是会返回一个字符串。因此,您可以使用神秘的 .toString
覆盖来让您的方法仍然返回父方法的副本 - 但也允许将它们视为字符串。
From this I can see why our answers aren't really adequate - and why you want to get rid of .data
. Happily, your .data
always returns a string, anyway. So, you can use the mystical .toString
override to have your methods still return a copy of the parent method - but also allow for them to be treated like strings.
以下是一个例子:[使用小提琴]
Here's an example: [with a fiddle]
var stringMagic = function() {
var chain = "",
self = this;
self.toString = function () { return chain; }; // Where the real magic happens.
self.add = function(str) {
chain += str + " ";
return self;
};
};
var magi = new stringMagic();
alert(magi.add("hello").add("world")); // Alerts, "hello world"
magi.add("and").add("thanks").add("for").add("all").add("the").add("fish");
alert(magi); // Alerts, "hello world and thanks for all the fish"
在你的情况下,可能你们所有人我必须做的是将 .data
更改为 P
改为 .toString
并将其包装在一个函数中。
In your case, probably all you'd have to do is change .data
in P
to .toString
and wrap it in a function.
将来当你添加对其他数据类型(如数字和布尔值)的支持时,你可以使用 valueOf
与使用 toString
的方式相同。实际上,当返回值不是字符串时,你还应该继续包含 toString
,因为他们将该数字视为字符串 - 就像 console.log
或 $。fn.text
。以上是上面的示例,但有数字: http://jsfiddle.net/emqVe/1/
In the future when you add support for other data types such as numbers and booleans, you can use valueOf
in the same way you use toString
. In fact, you should also continue to include toString
when the return value is not a string for when they're treating that number as a string - like in console.log
or $.fn.text
. Here's the example above, but with numbers: http://jsfiddle.net/emqVe/1/
这篇关于如何在JavaScript中检测方法链的结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!