请问外部怎么调用 shool 属性下的:pSchool,mSchool,college ???
var r1=new ren("王二狗",20,"");
console.log( r1.age );
console.log( r1.name );
console.log( r1.pSchool);
r1.say();
function ren(name,age,sex)
{
this.name=!name?"某r1":name;
this.age=!age|age>120|age<=0?1:age;
this.sex=sex=="MAN"|sex=="WOMAN"?sex:"UNKNOW";
this.school=schoolF();
function schoolF()
{
this.pSchool="五七小学";
this.mSchool="实验小学";
this.college="五七小学";
console.log("【我是shool方法】,子属性是【"+pSchool+"】【"+mSchool+"】【"+college+"】");
}
this.say=function()
{
console.log("【我是say方法】,我的名字是"+this.name+",性别是"+this.sex+",年龄是"+this.age+",小学是"+mSchool);
}
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
在构造函数
ren中,函数schoolF相当于一个闭包;JavaScript 有一个众所周知的坑就是闭包内的this会指向全局,所以你在schoolF里的属性实际上设给了window。解决的办法也很简单,就是在
schoolF外面先把this保存起来:不过看你题目的意思,
school是ren的属性,然后pSchool是school的属性?那你得用new调用school才行(楼上也说了)。你的school是直接调用,不是new出来的,所以没有属性,应该是undefined
前两位已经说了