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.

Answers:

Answer

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:

myObject.foo().bar();

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

myObject.foo();
myObject.bar();

But requires less typing.

Here is a more complete example:

function AnimalSounds() {}

AnimalSounds.prototype.cow = function() {
    alert("moo");
    return this;
}

AnimalSounds.prototype.pig = function() {
    alert("oink");
    return this;
}

AnimalSounds.prototype.dog = function() {
    alert("woof");
    return this;
}

var sounds = new AnimalSounds();

sounds.cow();
sounds.pig();
sounds.dog();

sounds.cow().pig().dog();

http://jsfiddle.net/jUfdr/

Answer

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

MyObject.method1().method2().method3();

Real world example: jQuery

$(this).addClass('myClass').hide();
Answer

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.

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.