3

I'm currently working in a js-component and i was wondering if there's a better way to concatenate functions in javascript then returning this. I have a sample code working here, and that's how i solved the problem.

function hi(){
  console.log('hi');
  return this;
}
function bye(){
  console.log('bye');
  return this;
}
function Test(){};

Test.prototype.hi = hi;
Test.prototype.bye = bye;

var x = new Test();

x
 .hi() //hi
 .bye(); //bye
5
  • 3
    Was one of those prototypes meant to be adding bye? Commented Oct 9, 2015 at 16:19
  • 4
    I'm pretty sure there isn't any other way, let alone a better one. Commented Oct 9, 2015 at 16:19
  • 2
    By concatenate, I think you mean chain? Commented Oct 9, 2015 at 16:23
  • Also, you need to quantify "better" if you want an objective answer. Otherwise, this question risks closure as "primarily opinion based". See How to Ask. Commented Oct 9, 2015 at 16:25
  • 1
    In order to make method chaining work, you have to return the object that implements the interface you want to chain. And that's this. Not really anything else you can do. Commented Oct 9, 2015 at 16:27

1 Answer 1

6

This is a well known pattern called a fluent interface - it can certainly help write code in certain circumstances, but like everything it has a purpose but shouldn't be used for everything.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.