JavaScript 对象方法链接:有用吗?

发布于 2024-07-14 08:12:36 字数 532 浏览 10 评论 0原文

所以...在 JavaScript 中搞乱了一个对我来说很新的想法,让对象的方法返回它们是方法的对象; 这就会导致可链接性。 那么我的问题是:这有什么用处? 我把它放在一起来测试基本的工作原理:

<script>
MathChain = function()
 {
    this.pass = function()
     {
        this.multiply = eval(arguments.join('*'));
        this.add = eval(arguments.join('+'));
        return this;
     }
 }

m = new MathChain().pass(5, 10, 20).multiply; // 1000
a = new MathChain().pass(5, 10, 20).add;      // 35
</script>

这显然不是一个使用这个概念的非常有效的实例,所以你能给我指出一些可以正确执行此操作的东西吗(请除了 jQuery 之外)?

So... messing around in JavaScript with an idea that's new to me, having methods of an Object return the Object of which they are methods; this then leads to chainability. My question, then: how can this be useful? I threw this together to test the fundamental workings:

<script>
MathChain = function()
 {
    this.pass = function()
     {
        this.multiply = eval(arguments.join('*'));
        this.add = eval(arguments.join('+'));
        return this;
     }
 }

m = new MathChain().pass(5, 10, 20).multiply; // 1000
a = new MathChain().pass(5, 10, 20).add;      // 35
</script>

That's obviously not a viciously efficient instance in which one would use this concept, so could you point me to something that does do so properly (aside from jQuery, please)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

所谓喜欢 2024-07-21 08:12:36

好吧,这是一个不太现实的适用示例,但我想您会明白的。 如果允许您对一个对象执行许多不同的操作,并提供了便利。

var truck = function() {

    this.turnLeft = function {

       // turn left
       return this;

    }

    this.turnRight = function {

       // turn right
       return this;

    }

    this.goReallyFast = function {

       // go fast!
       return this;

    }

};

// My get-away plan
var myTruck = new truck();
myTruck.turnLeft().turnRight().goReallyFast();

Well, here is a not very real-world applicable example, but I think you'll get the idea. If allows you to do a number of different operations on an object, and provides convenience.

var truck = function() {

    this.turnLeft = function {

       // turn left
       return this;

    }

    this.turnRight = function {

       // turn right
       return this;

    }

    this.goReallyFast = function {

       // go fast!
       return this;

    }

};

// My get-away plan
var myTruck = new truck();
myTruck.turnLeft().turnRight().goReallyFast();
一百个冬季 2024-07-21 08:12:36

对于一个非常不同的(非 OO)示例,链接有点类似于 Unix 管道 。 Unix 管道的每个步骤都会返回完整的(修改后的)内容,适合发送到下一步:

cat file1 file2 | sort -n | awk '{print $2}' | sed 's/@/ at /g'

For a very different (non-OO) example, chaining is somewhat analogous to Unix pipelines. Each step of a Unix pipe returns the full (modified) content, suitable for sending on to the next step:

cat file1 file2 | sort -n | awk '{print $2}' | sed 's/@/ at /g'
只是在用心讲痛 2024-07-21 08:12:36

流畅的界面 - http://en.wikipedia.org/wiki/Fluent_interface

是的,我认为可以非常有用,但就像任何设计模式一样,只应在需要时使用

编辑:这里是使用流畅界面的 C# 中的 twitter 客户端 api - http://code.google.com/p/tweetsharp/

Fluent interface - http://en.wikipedia.org/wiki/Fluent_interface

Yea I think it could be very useful but like any design pattern should only be used when needed

Edit: here is twitter client api in c# using a fluent interface - http://code.google.com/p/tweetsharp/

他是夢罘是命 2024-07-21 08:12:36

它有用的一个例子是您的问题略有不同 - 您将对象设计为不可变,而不是返回相同的对象。 然后,您的函数都将返回相同类型的新实例,但属性已正确设置。

这有许多实际应用,特别是在函数式编程领域。

One example where it's useful is with a slight variation on your problem — instead of returning the same object, you design the object to be immutable. Then your functions will all return a new instance of the same type, but with the properties already set appropriately.

This has many practical applications, especially in the realm of functional programming.

萌酱 2024-07-21 08:12:36

虽然它的工作方式与您的示例不同(说实话,我以前从未见过它这样做过),jquery 认为“链接”非常有用,并且 jquery 几乎是当今 JS Web 框架的标尺......所以是的:-)

While it doesn't work in the same way as your example (TBH I've never seen it done that way before), jquery considers "chaining" to be very useful, and jquery is pretty much the yardstick these days when it comes to JS web frameworks... so yeah :-)

停滞 2024-07-21 08:12:36

我在寻找使方法在定义后可链接的通用解决方案时发现了这个问题。 这就是我的想法。 我是 JavaScript 新手; 买家要小心。

makeChainable = function() {
    var receiver = arguments[0]
    for (var i = 1; i < arguments.length; i++) {
        functionName = arguments[i];
        (function() {
            wrapped = receiver[functionName];
            receiver[functionName] = function() {
                wrapped.apply(receiver, arguments);
                return receiver;
            }
        })();
    }
}

daisy = {
    name: 'Daisy',
    moo:  function() { console.log(this.name + " moos!") }
}

makeChainable(daisy, 'moo');
daisy.moo().moo().moo();

I found this question while searching for a general solution to making methods chainable, after they are defined. Here's what I came up with. I am a JavaScript neophyte; buyer beware.

makeChainable = function() {
    var receiver = arguments[0]
    for (var i = 1; i < arguments.length; i++) {
        functionName = arguments[i];
        (function() {
            wrapped = receiver[functionName];
            receiver[functionName] = function() {
                wrapped.apply(receiver, arguments);
                return receiver;
            }
        })();
    }
}

daisy = {
    name: 'Daisy',
    moo:  function() { console.log(this.name + " moos!") }
}

makeChainable(daisy, 'moo');
daisy.moo().moo().moo();
你是暖光i 2024-07-21 08:12:36

在 JavaScript 中,当浏览 DOM 时,这种情况总是会出现。 特别是当你试图费力地浏览一堆没有 id 的元素时。

例如,有一个关于查找表的第一个元素。 它可能涉及大量循环或链式命令。

In JavaScript this comes up all the time when navigating the DOM. In particular when trying to wade your way through a bunch of elements that don't have ids.

For example there was a question on SO regarding finding the first element of a table. It can involve a lot of loops or chained commands.

七分※倦醒 2024-07-21 08:12:36

如果您想对单个对象执行一系列操作,JavaScript 链接会非常有用。 我同意下面 Michael Luton 的观点,链接应该小心处理。 如果将一两个链接方法添加到仍然可读的对象上。 如果您开始添加四个、五个甚至九个,那么您的代码不仅会变得更难阅读,而且更难维护。

JavaScript chaining can be very useful if you want to preform a series of actions on a single object. I agree with Michael Luton below, chaining should be handled with care. If you add one or two chained methods onto an object that is still readable. If you start adding four, five, or even nine, then your code becomes harder not only to read but to maintain.

等数载,海棠开 2024-07-21 08:12:36

所有的孩子都喜欢链条。 然而,根据我的经验,应该谨慎使用它,因为它会降低代码的可读性。 换句话说,做对你有意义并且可以被基本熟悉该概念的其他程序员轻松理解的事情。

All the kids love chaining. However, in my experience it should be used with care since it can decrease the readability of the code. In other words, do what makes sense to you and can be easily understood by other programmers who have a basic familiarity with the concept..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文