JavaScript function chaining using the singleton pattern -


i have small piece of code written in below.

var = || {};  my.farm = (function () {      var add = function(x){         console.log(x)         return + this;     };      return {         add: function(x){             return add(x);         }      } }); 

on separate file create sheep instance of my.farm

var sheep = new my.farm() 

i want able call function following output 6

sheep.add(3).add(2).add(1) 

any ideas how can achieve this? changes required my.farm snippet accommodate this?

thanks in advance.

something this

var = || {};  my.farm = (function () {     var x=0;     return {         add: function(newx){             if(typeof(newx) !="undefined") {                 x+=newx;                 return this;             }             return x;        }     } });  var sheep = my.farm(); console.log( sheep.add(2).add(4).add()); 

http://jsfiddle.net/7q0143er/


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -