Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Object Method Chaining: useful? [closed]

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)?

like image 290
Hexagon Theory Avatar asked Mar 02 '09 18:03

Hexagon Theory


People also ask

Why is method chaining important?

Method chaining eliminates an extra variable for each intermediate step. The developer is saved from the cognitive burden of naming the variable and keeping the variable in mind.

Can you chain JavaScript methods?

Method chaining, or simply chaining, in JavaScript can be defined as when one or more sequential methods get invoked from an object without the introduction of unnecessary variables. The sole purpose of chaining is to make our code more readable and reduce the redundancy within.

Why is method chaining bad?

The drawback to self-referential method chaining is that you communicate that multiple method calls are required to do something, and that each call builds off the last. If this is not true, then method chaining could be communicating the wrong thing to other programmers.

When was optional chaining added to JavaScript?

Optional chaining was introduced in ES2020. According to TC39 it is currently at stage 4 of the proposal process and is prepared for inclusion in the final ECMAScript standard.


1 Answers

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();
like image 153
jonstjohn Avatar answered Oct 07 '22 02:10

jonstjohn