简体   繁体   中英

How can I call any function in a chain of functions, without the chaining?

Sorry if my question wasn't clear enough. I'll put my code here...

var chain = {
    'fn_1' : {
             //fn_1 code here
             chain.fn_2();},
    'fn_2' : {
             //fn_2 code here
             chain.fn_3();}

...and so on
}

Let's say if i wana call chain.fn_1(), is there a way I can do that without calling chain.fn_2()?

What I can think of right now is a flag, but that would be alot of excess flags probably for each function. Do you guys have any ideas?

If the series of functions each call the next one you're correct, you'd need to have some sort of flag. In all likelihood, what would be best would be to modify your functions so that they return the reference to the object. Then you could chain like so:

var chain = {
  'fn_1': function () {
    // do something here.
    return this;
  },
  'fn_2': function () {
    // do something here.
    return this;
  },
  'fn_3': function () {
    // do something here.
    return this;
  }
};

// call the full chain:
chain.fn_1().fn_2().fn_3();

// call only the middle.
chain.fn_2();

gddc's answer is best, but if you can't modify the object for some reason, you could do this:

var _oldFn2 = chain.fn_2
chain.fn_2 = function() { return; };
chain.fn_1();
chain.fn_2 = _oldFn2;
var chain = {
    fn : ['fn1', 'fn2', 'fn3'],
    call : function(name) {
       var i = 0, pos = -1, l = this.fn.length;
        for(i = 0; i < l; i += 1) {
            if(this.fn[i] == name) {
                pos = i;
            }
            if(pos !== -1) {
                this[this.fn[i]]();             
            }
        }

    },
    fn1 : function() {
        alert('fn1');
    },
    fn2 : function() {
        alert('fn2');
    },
};
chain.call('fn1'); //chain
chain.fn1(); //single

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM