为什么在构造函数中注释/取消注释 alert() 会切换变量作为 obj 实例的一部分 [英] Why commenting/uncommenting alert() in constructor toggles variable as part of the obj instances

查看:25
本文介绍了为什么在构造函数中注释/取消注释 alert() 会切换变量作为 obj 实例的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,如果我在构造函数中注释 //alert("Your Name is: " +fname); 然后 'alert(p1.fname);alerts "Suresh",如果我删除注释掉alert("Your Name is: " +fname);然后浏览器控制台给出错误:fname is not defined`

In the following code, if I comment //alert("Your Name is: " +fname); in the constructor function then '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 is not defined`

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

  var p1 = new person();

  alert(p1.fname);

我对这种行为感到困惑.请解释一下

I am puzzled by this behaviour. Pls explain

谢谢

推荐答案

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

You're using a variable that doesn't exist in the first alert(), so get you an error message telling you the variable is not defined`

person() 函数内部没有名为 fname 的变量,它叫做 this.fname,就像你创建的一样>

There is no variable named fname inside the person() function, it's called this.fname, just like you created it

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

  var p1 = new person();

  alert(p1.fname);

FIDDLE

这篇关于为什么在构造函数中注释/取消注释 alert() 会切换变量作为 obj 实例的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆