Skip to content

Instantly share code, notes, and snippets.

@iladarsda
Created March 13, 2014 12:51
Show Gist options
  • Save iladarsda/9527884 to your computer and use it in GitHub Desktop.
Save iladarsda/9527884 to your computer and use it in GitHub Desktop.
JavaScript - method chaining
$.fn.redBorder = function () {
$(this).css("border", "1px solid red");
return this;
// or shorter "return $(this).css("border", "1px solid red");"
};
$.fn.greyBackground = function () {
return $(this).css("background-color", "grey");
};
$.fn.innTxt = function (txt) {
return $(this).html(txt);
};
$('#main').redBorder().greyBackground().innTxt("testing chaining");
var value = 0;
var obj = {
increase: function(val) {
value = value + val;
return obj;
},
decrease: function(val) {
value = value - val;
return obj;
}
}
obj.increase(5).increase(2).decrease(1);
console.log(value); // 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment