Autoplay

    this in Function Calls

    Marius SchulzMarius Schulz

    In most cases, the value of a function's this argument is determined by how the function is called. This lesson explains what this refers to when we call plain function. Marius points out how functions behave differently in strict and non-strict mode. "use strict" mode defaults this to undefined and prevents us from assigning values to undefined. We must call functions as a constructor to assign their this value correctly.

    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 00:00 In most cases, the value of a function's this argument is determined by all the function is called. That means, the this value may be different each time the function is executed. Let's look at a plain and decorated function call.

    00:15 If we're not in strict mode, a plain function call sets the function's this value to the global object. If we're in strict mode, a plain function call sets the function's this value to undefined. It doesn't matter whether are not the cause side is in strict mode. It all depends and whether or not the function is in strict mode.

    00:42 The distinction will become relevant for you, if for example, your code is written in strict mode, but some third party library that you're using is not. Let's now see, why it makes sense for the this value to be undefined in strict mode.

    01:01 Here is a simple person function that accepts two parameters and initializes two properties. Note that this piece of code is not in strict mode. If we invoke the person function using a plain function call, the result probably isn't what we intended. The person variable holds the value undefined.

    01:25 Since we're not in strict mode, this within the function refers to the global object. Therefore, we assigned first name and last name to global. This is unfortunate, because it's almost never the desired behavior. Let's contrast this with strict mode where the this value within the function is set to undefined.

    01:48 Now, we get an error when invoking the person function using a plain function call, because we cannot assign properties to undefined. That prevents us from accidentally creating global variables, which is a good thing. The uppercase function name is a hint to us. That was supposed to call it as a constructor. We do that using the new operator.

    02:10 Now, we correctly construct a new person, and we also no longer pollute the global object with the first name and last name properties.

    Discuss

    Discuss