Search code examples
method-chaining

Method chaining, which is run first?


This is not a duplicate of When chaining methods in PHP, Is it possible to determine which method was called first?


I wonder if there is a general rule for the order of execution in method chaining? When running the following code:

obj.method1().method2();

Which is run first: method1() or method2()?

I assume method1() must necessary be called before method2(). Otherwise, since method1() is not already called, method2() has no returned object to process. Here is an experimental confirmation for JavaScript : http://jsfiddle.net/Imabot/sjo9gxfq/60/

But, I found an example against the previous statement with D3.js, where the objects seems selected before being created:

d3.select('body')
    .selectAll('p')
    .data(dataset)
    .enter()
    .append('p')
    .text('Paragraph');

Which is called first?


Solution

  • Methods are called from left to right.

    D3.js is a particular case, this article explains nicely what happens: Thinking with Joins