5

I have an object I created with this snip-it that looks like this:

  ...
  var steps = new Array();
  this.createStep = function(){steps.push(new step()); return steps[steps.length-1];}; 
  this.getSteps = function(){return steps;}; //returns Array
  this.removeStep = function(pos){steps.splice(parseInt(pos), 1);}; // integer possition zero base
  this.insertStep = function(pos){steps.splice(parseInt(pos),0, new step());};

And this works fine:

...
var newStep = wfObj.createStep();
newStep.setTitle('Step-'+i);
newStep.setStatus('New');

but this does not

var newStep = wfObj.createStep().setTitle('Step-'+i).setStatus('New');

Could someone please tell me how to fix this or even what to call it when you chain methods like this?

3
  • Your setters would need to return the object. Commented Sep 25, 2011 at 22:22
  • 2
    @DaveNewton: Why don't you write that as an answer? Commented Sep 25, 2011 at 22:23
  • @NedBatchelder Too short; not worth it. Commented Sep 25, 2011 at 22:33

2 Answers 2

6

This is called a fluent interface. The way to make it work is to have every function return this.

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

Comments

4

As Ned said, this is sometimes called fluent interface. It's also sometimes called method chaining, as you have heard.

You probably have some code somewhere that looks like this:

this.setTitle = function(newTitle) {
    title = newTitle;
};

Change that to this:

this.setTitle = function(newTitle) {
    title = newTitle;
    return this;
};

Do the same for setStatus.

1 Comment

Thank you everyone you're the best! Sometimes knowing what to call it can make all the difference.

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.