4

I have a function that is bound to a React component:

    functionName(param1, param2 = this.state.field) {

    }

I've never heard of the 'this' keyword being used within a function signature in Javascript and am wondering if the context of 'this' will be the containing object or the global scope. Does this function need to be bound to the proper context before I can use 'this' properly within the signature?

Zachary Bennett
  • 932
  • 9
  • 15
  • What are you trying to bind the `this` context to? The component? The function? The global object? – mhodges Jul 11 '17 at 17:02
  • Nothing. I'm simply trying to determine if the context of this within the function signature will be the context of the containing object (the react component the function itself is bound to) – Zachary Bennett Jul 12 '17 at 02:17

2 Answers2

2

I am wondering if the context of 'this' will be the containing object or the global scope.

Neither. Default values are not evaluated outside the function, but inside the call. The this keyword will point to the same value it would in the body of the method - the receiver of the call. So if the function was bound to your react component, that is what this will be.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Ah that makes sense! I didn't know that the default value was set inside the function body. Thanks for knowledge. So I'm guessing if the function is not bound to anything then the context of this will be the containing object... unless the function is a nested unbound function – Zachary Bennett Jul 12 '17 at 02:48
1

If the function is within a class that is extending the React.Component class from react library. "this" keyword refers to the current object in context of it's class. For example:

import React from 'react';
class example extends React.Component {
    this.state = {
        field: "this variable!"
    }
    functionName(param1, param2 = this.state.field) {
        console.log(param2);
    }   
}

As you observe, this.state is a property of example class simply being called at the second argument, which will return the value of the field property of this.state object.

If you wonder it is doable or not. Well, JavaScript is a multi-paradigm language, and if intended to use it in a functional paradigm, this can definitely be acceptable.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
Trishant Pahwa
  • 2,559
  • 2
  • 14
  • 31