What does “return this” do within a javascript function?

i wonder, what does "return this" do within a javascript function, what's its purpose? supposing we have the following code:

Function.prototype.method = function (name, func) {
  this.prototype[name] = func;
  return this;

What does "return this" do inside of a function?

I know what code above does, and what is the use of "this" keyword. I just don't know what "return this" does inside of a function.



It refers to the object instance on which the method is currently being called. It's used for chaining. For example, you could do something like this:


Since foo returns this (a reference to myObject), bar will be called on the object too. This is the same thing as doing


But requires less typing.

Here is a more complete example:

function AnimalSounds() {}

AnimalSounds.prototype.cow = function() {
    return this;

AnimalSounds.prototype.pig = function() {
    return this;

AnimalSounds.prototype.dog = function() {
    return this;

var sounds = new AnimalSounds();





It means the method will return the object it belongs to. This can be useful if you want to chain instructions like so:


Real world example: jQuery


tl;dr returning this from a method is a common way to allow "chaining" of methods together.

this refers to the current context, and changes meaning depending on the manner in which you're invoking a function.

With function invocation, this refers to the global object, even if the function is being invoked from a method, and the function belongs to the same class as the method invoking it. Douglas Crockford has described this as "mistake in the design of the language" [Crockford 28]

With method invocation, this refers to the object on which the method is being invoked.

With apply invocation, this refers to whatever you set it to when calling apply.

With constructor invocation, this refers to the object that is created for you behind the scenes, which is returned when the constructor exits (provided you don't misguidedly return your own object from a constructor).

In your example above, you're creating a new method called method that allows you to add functions dynamically, and returns this, thereby allowing chaining.

So you could do something like:

Car.method("vroom", function(){ alert("vroom"); })
   .method("errrk", function() { alert("errrk"); });

and so on.


It returns this, usually meaning the html element that called it, but "this" can have various meanings http://www.quirksmode.org/js/this.html


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.