I have been coding in jQuery for a while now , And one thing that really fainates me about jQuery is the way it is able to chain methods, I just decided to make my own set of chainable methods, In pure js of course and well, It does't do anything useful, have a look:
var me = {};
function add() {
this.color = 'red';
return this;
}
function value() {
this.value = 50;
return this;
}
var s = add.call(me);
console.log(me);
What i wanted to achieve was a syntax, like so,
me.add().value(); // value should be Object { color: "red" , value : 50 }
Well, how do i achieve that kind of syntax ?
As of now i have to use the call()
to forcefully change the context of the functions add()
and value()
, can somebody tell me please ?
THIS article kind of helped me in understanding that it is important to return this
, but i am still unable to understand how i can use chaining in my scenario as of now.
Any help and advice will be highly appreciated.
EDIT:: This might sound crazy, but i am already aware of syntax like below:
var obj =
{
f1: function() { ...do something...; return this;},
f2: function() { ...do something...; return this;}
}
if you observe the above code this indeed will be pointing to the main object(obj) , but what if i have a obj2 ?? got to use call()
or apply()
now ? that's not what i want and hence i would like the functions to not be closure's inside the object, but rather independent functions, that can be called on any object, like so:
me.add().value(); // value should be Object { color: "red" , value : 50 }
Is this possible ?
Thank you.