What's the difference

between these two functions with THIS and w/o it:

let val = 10;
function print(val){
    if (val === 10){
        return val + 1;
    } else {
        return val;
    }
}

console.log(print(val))  --> 11

function anotherPrint(val){
    this.val = val;
    if (this.val === 10){
        return this.val + 1;
    } else {
        return this.val;
    }
}

console.log(anotherPrint(val))   --> 11

THIS keyword

This video is what helped me get a better understanding of what the this keyword actually meant.

If you enjoy reading more than watching, W3 Schools provides a fantastic section on what the this keyword actually means.

It’s very hard to describe what exactly the this keyword actually means because it has different values depending on where it is used.

If we run the second method we have provided, and just console.log(this) at the start we will see that it is referencing the window object. This is because this references the global object. Because you say this.val = val; you’re assigning a key of val to the window object. Try and console.log(this) after you have run this.val = val and look to see that the window object has a key of val.

I would continue to explore using the this keyword and console.log(this) as you are working on your code to see exactly what this is referencing.

I hope this is of some use! There are concepts covered in the video that @alkapwn3d posted that the video I have provided does not.

Best of luck and happy coding!

1 Like

also this — by Javascript.info

ps. i love Mosh

2 Likes

I’ve tried console.log(this) everywhere and it throws window object in the console.
As I understand it so in the first case I bind it to the global context, and in the second one only to execution context. Am I right or no, I don’t know.

When you run anotherPrint() You’re saying this.val = val an easier way to see this is Window.val = val. Once you run that function and console.log(this) after it, you will notice that the Window object now has a key of val that is set to 10. This means that after you have run that function, if another function calls this.val it will be 10.

Remember that a function will always give you the Window object as this because functions are in the global context. I would recommend that you create an object that defines a function. Because that function is within an object it is considered a method. If you console.log(this) within that method, it will return the parent object. I’ll provide you with the snippet. Sorry if this is overkill!

const anObject = {
    a: 'Test',
    b: 'Test',
    c: 'Text',
    thisTest: function () {
        console.log(this)
    }
}
anObject.thisTest()
1 Like

Unless 'use strict' is enabled, in which case you will get undefined. Moral: always add 'use strict'

(if you’re writing an ES6 class, strict is enabled implicitly)

1 Like