0

While learning how this keyword works in JS using VSCode, I came across a tutorial code (below). After executing the code in VSCode the Output I got doesn't match the Output of tutorial or an Online JS editor.

    var firstName = "Peter",
    lastName = "Ally";

    function showFullName () {
    console.log (this.firstName + " " + this.lastName);
    }

    var person = {
    firstName   :"Penelope",
    lastName    :"Barrymore",
    showFullName:function () {
    console.log (this.firstName + " " + this.lastName);
    }
    }

    showFullName (); // ** problem is here ** 
    person.showFullName (); 

While executing the program in the latest version of VSCode :

The output is Undefined Undefined and Penelope Barrymore

But in the tutorial and Online JS Editor (https://playcode.io/online-javascript-editor) the Output is :

Peter Ally and Penelope Barrymore

I'm stuck here, Please Explain what is correct and why?

Thanks.

VLAZ
  • 18,437
  • 8
  • 35
  • 54
heeat
  • 128
  • 1
  • 9
  • In the online editors, the top level must be the window, so variables declared there get put onto the window, which is referenceable via `this` when a function is called without a calling context in non-strict mode. In your VSCode, it sounds like the top level of your code is not at the very top when the JS gets executed – CertainPerformance Sep 29 '19 at 11:39
  • @CertainPerformance ok, what should i follow now the VSCode or Online Editors or is there any workaround so that it would work in VSCode aswell – heeat Sep 29 '19 at 11:43
  • 1
    Using `this` to refer to the global object in non-strict mode is almost never a good idea (and implicitly putting variables onto the global object is also a bad idea). I don't know what your objective is, but consider a different approach – CertainPerformance Sep 29 '19 at 11:46

0 Answers0