对象'未设置的数据成员值

Object's data member value not set

本文关键字:数据成员 设置 对象      更新时间:2023-09-26

在设置数据成员的值后,我得到了意外的输出。这种行为背后的理由是什么?

function studentClass(id, name) 
{
    this.id = id;
    this.name = name;
    this.print = function() { 
        alert(id + ": " + name);
    }
}
var s = new studentClass(101, "Vijay");
s.print();     // 101, Vijay
alert(s.id);   // 101
alert(s.name); // Vijay
s.id = 102;
alert(s.id);  // 102 
s.print();    // 101, Vijay Why?

https://jsfiddle.net/00d1cvxL/5/

您应该在print函数中使用alert(this.id + ": " + this.name);。早些时候,它显示了您传递给studentClass的参数idname