What does "return this" do within a javascript function?

Asked
Active3 hr before
Viewed126 times

9 Answers

functionjavascriptwithinreturn
90%

i wonder, what does "return this" do within a javascript function, what's its purpose? supposing we have the following code:,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., 1 i know the use of "this" keyword i just don't know what is the use of "return this" inside of a function . – user722756 Nov 28 '11 at 19:23

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();

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();
load more v
88%

Inside a function, the value of this depends on how the function is called. ,Destructuring assignment, To set the value of this to a particular value when calling a function, use call(), or apply() as in the examples below. , When a function is called as a method of an object, its this is set to the object the method is called on.

this
load more v
72%

In a function, this refers to the global object.,In a method, this refers to the owner object.,Alone, this refers to the global object.,In an object method, this refers to the "owner" of the method.

What is this?

The JavaScript this keyword refers to the object it belongs to.

this
load more v
65%

Important JavaScript concepts explained in simple words,A single JavaScript file may contain both strict and non-strict modes. So it is possible to have different context behavior in a single script for the same invocation type:,When executing new RegExp('\\w+') and RegExp('\\w+'), JavaScript creates equivalent regular expression objects.,5.1. this in an indirect invocation

A simple example of function invocation:

javascriptfunction hello(name) {
   return 'Hello ' + name + '!';
} // Function invocationconst message = hello('World');
load more v
75%

An arrow function makes an implicit return; in this case, the return keyword will be optional.,Using the arrow function, curly braces, parenthesis, function, and return keywords become optional.,The keyword return would indeed be optional. The Arrow function has an implicit return. Thus no curly braces. If you are using the curly braces, you have to use the return statement.,Curly brackets are optional, and since we have one statement, we can do away with the return keyword.

// a named regular function
function myFunc(params) {
   // function body
}
load more v
40%

While parameters are used to pass one or more values into a JavaScript function, you can use a return value to pass a value out of the function as well. The function can use the return statement to exit and pass some value back to the caller when it’s completed execution.,Here’s an example of passing a variable as a parameter to a function call, and another that passes the return value of a function directly to the parameters of another function:,Here’s an example of a JavaScript function with a return value:,Once the return value has been captured into a variable, that variable can then be used like any other variable. You can consume it’s value directly in this code for something, or even pass it as a parameter to another function.

function sayHello(name) {
   // implementation code here
}
load more v
22%

Constructor functions technically are regular functions. There are two conventions though:,If we have many lines of code all about creation of a single complex object, we can wrap them in an immediately called constructor function, like this:,Constructor functions or, briefly, constructors, are regular functions, but there’s a common agreement to name them with capital letter first.,We can use constructor functions to make multiple similar objects.

function User(name) {
   this.name = name;
   this.isAdmin = false;
}

let user = new User("Jack");

alert(user.name); // Jack
alert(user.isAdmin); // false
load more v
60%

In practice, you often need to create many similar objects like a list of persons.,To do this, you can use a constructor function to define a custom type and the new operator to create multiple objects from this type.,Note that ES6 introduces the class keyword that allows you to define a custom type. And classes are just syntactic sugar over the constructor functions with some enhancements.,To resolve this, you can use the prototype so that all instances of a custom type can share the same method.

In the JavaScript objects tutorial, you learned how to use the object literal syntax to create a new object:

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
let person = {
   firstName: 'John',
   lastName: 'Doe'
};
Code language: JavaScript(javascript)
load more v
48%

Arrow functions are great because the inner value of this can't be changed, it's always the same as the outer this.,With arrow functions, the value of this can't be changed with bind:,With arrow functions, the value of this can't be changed with call or apply:,With arrow functions, the value of this can't be changed by calling the function as a constructor:

const arrowFunction = () => {
   console.log(this);
};
load more v

Other "function-javascript" queries related to "What does "return this" do within a javascript function?"