Jason
Jason

Reputation: 403

Javascript object with methods

How would I make an object, that I can instruct what to do, at certain points. See example:

function bar(){
    // call/execute the start() code
    // do something
    // do some other thing
    // do something else
    // call/execute the end() code
}



foo=new bar();
foo()
.start(function(param){
    console.log("start");
})
.end(function(param){
    console.log("end");
})

Upvotes: -1

Views: 68

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

To chain function you need to return this or object itself you can try something like this

  • Here new bar() will return a function, foo() will return the obj,
  • On further start and end method call we update the property and return reference to object itself

function bar() {
  let obj = {
    value: [],
    start(func) {
      this.value.push('start')
      console.log(this.value)
      func()
      return this
    },
    end(func) {
      this.value.push('end')
      console.log(this.value)
      func()
      return this
    }
  }
  return () => obj
}



foo = new bar();
foo()
  .start(function(param) {
    console.log("start");
  })
  .end(function(param) {
    console.log("end");
  })

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386550

You could take some prototype functions and return instaead of an implicit this, a dunction with a bound this.

The functions use a fluent interface and returns this.

function Bar() {
    return function() {
        return this;
    }.bind(this);
}

Bar.prototype.start = function (fn) { fn(); return this; };
Bar.prototype.end = function (fn) { fn(); return this; };

var foo = new Bar();

foo()
    .start(function(param) {
        console.log("start");
    })
    .end(function(param) {
        console.log("end");
    })

Upvotes: 1

Related Questions