Javascript Practice Day 5 : Implementing Method Chaining
Implementation of Method Chaining
var obj= function(){
var i=0 ; //this is a closure and will be shared by all the function
var add= function(j){
i+=j; //this is the operation
return this; // we return the object as this will help in achieving method chaining
}
var subs = function(j){
i-=j; //this is the operation
return this; // we return the object as this will help in achieving method chaining
}
var print= function(){
console.log(i);
}
return { add: add, subs: subs,print:print}; //create and return an empty object with different function attached to it --Step1
};
var x= obj() //Since we are returning a object from the above constructor function as show in step1 we are not required to use new operator to create a new instance of the object.
x.add(3).subs(2).print();
var obj= function(){
var i=0 ; //this is a closure and will be shared by all the function
var add= function(j){
i+=j; //this is the operation
return this; // we return the object as this will help in achieving method chaining
}
var subs = function(j){
i-=j; //this is the operation
return this; // we return the object as this will help in achieving method chaining
}
var print= function(){
console.log(i);
}
return { add: add, subs: subs,print:print}; //create and return an empty object with different function attached to it --Step1
};
var x= obj() //Since we are returning a object from the above constructor function as show in step1 we are not required to use new operator to create a new instance of the object.
x.add(3).subs(2).print();
Comments
Post a Comment