一个关于js函数的问题

function Student(sn,sname){

Student.school;

Student.location;
this.sn=sn;

this.sname=sname;

}

Student.school="xx大学";

Student.location="xx市xx路";

s1=new Student("222222222","jhgfds");

document.writeln("Student对象的属性为:
");

for(var i in Student){

document.writeln("student的属性:"+i+"="+Student[i]+"
");

}

for(var i in s1){

document.writeln("s1的属性:"+i+"="+s1[i]+"
");

}

Student.prototype.display=function Student(){

document.writeln("学生s1的学号:"+Student.sn+"姓名"+Student.sname+"
学校:"+Student.school+"地址:"+Student.location);
}

s1.display();

结果为什么都是未定义啊

图片说明

这代码的可读性太差了。。。。

刚才没弄好格式,,不好意思

好习惯很重要,,,,,,,,,,,,,,,,,,,,,,

这个就是JS跟其他语言的差别之处了,你不能用其他语言的思想来理解JS,这种问题我以前看《JS高级程序设计的时候有讲过》,相关术语我忘记了,不过我可以这样跟你说,你定义的function Student所代表的的指针,跟你定义的s1代表的指针有点区别,导致你在prototype原型里面写的函数所代表的指针也不相同。

(1)Student函数体里面只有两个sn和sname是会被赋值的、将是会存在一个地址的,所以用s1来实例化Student的时候,只会对sn和sname赋值并保存下来,但是school跟location是NULL空值,就算有Student.location="xx市xx路"这句话也白搭,这不关s1的事,这只是Student的事;

(2)根据以上所说,你应该可以理解,为什么用for-in语句的时候,Student输出的属性只有school和localtion;而s1只有sn和sname;

(3)如果以上两点你都没明白的话,你试着将原型函数改一下:

Student.prototype.display=function (){
            document.writeln("学生s1的学号:"+this.sn+"姓名"+this.sname+"学校:"+this.school+"地址:"+this.location);
}

然后再运行一下看看会有什么不同,相信你会理解的


(4)另外,你的代码有个地方有点错误,就是Student.prototype.display 等于的应该是一个匿名函数,而非在 = 后面定义一个有函数名的函数

1.var s1=new Student("222222222","jhgfds");
2. Student.prototype.display=function (){
document.writeln("学生s1的学号:"+this.sn+"姓名"+this.sname+"学校:"+this.school+"地址:"+this.location);
}

sn,sname是实例属性,不是Student的属性(相当于oo语言的类静态属性)。为什么 "学校:" + Student.school + "地址:" + Student.location会undefined,因为你最后有重新申明了Student函数,覆盖了之前的属性了,去掉



    Student.prototype.display = function /*Student*/() {///////////////////////

        document.writeln("学生s1的学号:" + this.sn + "姓名" + this.sname + "学校:" + Student.school + "地址:" + Student.location);
    }