dimanche 21 juin 2015

Javascript chaining and passing arguments

I have read a lots about chained functions in JavaScript, somehow I am really confused if it is possible to pass an argument across the chain.

My main goal is to recreate a "jQuery like" behavior passing the first argument of a function when on chain.

Here is a rough example:

;(function(window) {
    var test = {};
    test.a = function(i){
        return i+1;
    };
    window.test = test

})(typeof window != 'undefined' ? window : undefined);

console.log( test.a(1)) //-> should output 2
console.log( test.a(1).a()) // -> should output 3
console.log( test.a(1).a().a()) // -> should output 4

PS I guess this could be resolve using prototypes as it is described here but I really don't want to mess up with prototypes nor to mention that using stored properties for the test object does not fill my needs.

Aucun commentaire:

Enregistrer un commentaire