What does 'return this' do
What does 'return this' do
by Nirvanachain
HTML
<!--
Helpful Link:
http://stackoverflow.com/questions/8300844/what-does-return-this-do-within-a-javascript-function
-->
<a href="http://stackoverflow.com/questions/8300844/what-does-return-this-do-within-a-javascript-function" target="_blank">Article</a>
JavaScript
function AnimalSounds() {
console.log('Constructer');
}
AnimalSounds.prototype.cow = function () {
console.log('Moo');
return this;
}
AnimalSounds.prototype.dog = function () {
console.log('Woof');
return this;
}
AnimalSounds.prototype.cat = function () {
console.log('Meow');
return this;
}
var sounds = new AnimalSounds();
sounds.cow();
sounds.dog();
sounds.cat();
// by returning 'this' we can chain the methods.
sounds.cow().dog().cat();