0

how do I achieve this with an object that has functions?

I would like to sometimes launch a function a simple way then other times i would like to launch with extra data and bypass the part that normally would happen.

like digging a little deeper...

myobj.ONEFUNC=function(data1,data2){
    var DIFF=function(data3){
        /*In here I need to use data1, data2 & data3*/
        /*If this happens don't do normal*/
        /*maybe*/return;
        }
    /*do normal code things*/
    }


myobj.ONEFUNC('data1','data2').DIFF('data3');

myobj.ONEFUNC('data1','data2');

1 Answer 1

1

In order for that call syntax to work, ONEFUNC must return a function.

myobj.ONEFUNC=function(data1,data2){
  var DIFF=function(data3){
    /*In here I need to use data1, data2 & data3*/
    /*maybe*/return;
  }

  /*do normal code things*/

  return {DIFF: DIFF};
}

"If this happens don't do normal" isn't going to work though. ONEFUNC runs, returns an object containing the function you want to then run, and then DIFF runs. So DIFF only runs after ONEFUNC is done. So you can't change how ONEFUNC runs based on whether you also call DIFF.


Perhaps instead, you want chaining? Chaining means each function on your objects returns itself, so that you can continue to call methods on that object.

myobj = {
  ONEFUNC: function(data1, data2) {
    this.data1 = data1;
    this.data2 = data2;
    // other stuff
    return this;
  },

  DIFF: function(data3) {
    this.data3 = data3;
    alert(this.data1 + this.data2 + this.data3);
    return this;
  }
};

mobj.ONEFUNC(1,2).DIFF(3); // alerts "6"

You still can't change how ONEFUNC runs after it ran though. You may have to rethink why you need to that...

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

9 Comments

but if i don't call diff when i run ONEFUNC what happens?
+1. You to completely match original line: return {DIFF:DIFF}; so you can use .DIFF(..
@BenMuircroft you can't change how ONEFUNC runs because anything you add to that statement operates on the return value of ONEFUNC.
@BenMuircroft Sorry I don't understand your question.
If you call ONEFUNC it will execute, always. ONEFUNC has no way to know what's being done with the value it returns. This is weird and painful because it's a bad idea. Whatever you are trying to do, I'll bet you a dollar there is a far more elegant way. But it's hard to recommend anything based on the info you provided so far.
|

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.