为什么构造函数中的 commenting/uncommenting alert() 将变量切换为 obj 实例的一部分

Why commenting/uncommenting alert() in constructor toggles variable as part of the obj instances

在下面的代码中,如果我在构造函数中注释 //alert("Your Name is: " +fname); 然后 'alert(p1.fname);alerts "Suresh" and If I remove the comment out thealert("Your Name is: " +fname);then browser console gives out the error: fname 未定义`

function person () {
    this.fname = "Suresh";
    alert("Your Name is: " +fname);
  }

  var p1 = new person();

  alert(p1.fname);

我对这种行为感到困惑。请解释

谢谢

您正在使用第一个 alert() 中不存在的变量,因此收到一条错误消息,告诉您变量未定义`

person() 函数中没有名为 fname 的变量,它被称为 this.fname,就像您创建它一样

function person () {
    this.fname = "Suresh";
    alert("Your Name is: " + this.fname);
  }

  var p1 = new person();

  alert(p1.fname);

FIDDLE