1

//can anyone explain why is my output undefined.I am trying to figure it out what are the issues over here i am sorry i am new to javascript.

function Person() {
        this.name = 'Jack',
        this.age = 25,
        this.sayName = function () {
    
            //enter code here this is accessible
            console.log(this.age);
    
            function innerFunc() {
    
                // this refers to the global object
                console.log(this.age);
                console.log(this);
            }
            
            innerFunc();

        }
    }
    
    let x = new Person();
    x.sayName();
    
    Output:
    25
    undefined
    Window {}
  • 1
    In normal functions, the value of `this` is determined by how you call a function. The code `innerFunc();` doesn't specify what `this` should be, so it defaults to the `window` object (or undefined in strict mode). `window.age` is undefined. For comparison, in the code `x.sayName();`, the `x.` part specifies that `this` should be `x`. – Nicholas Tower Mar 03 '22 at 04:00
  • _"this refers to the global object"_: that function has its own `this` context depending on how it's called. And there are some typos in your code. those first two lines should end with semi-colons, not commas. Also, in general terms of the code it's probably not a good idea to have an inner function inside a constructor method. – Andy Mar 03 '22 at 04:03

1 Answers1

0

The inner function innerFunc does not know what this means so it specifies the global this. You can bind this with innerFunc

function Person() {
  this.name = 'Jack';
    this.age = 25;
    this.sayName = function() {
      console.log(this.age);

      function innerFunc() {
        console.log(this.age);
        console.log(this);
      }
      innerFunc.bind(this)();
    }
}
let x = new Person();
x.sayName();
brk
  • 48,835
  • 10
  • 56
  • 78