<script>
// 创建对象
function Student(room, group, name, age, address, teacher, course) {
this.room = room;
this.group = group;
this.name = name;
this.age = age;
this.course = course;
this.teacher = teacher;
this.adress = address;
this.attendClass = function (subject) {
return subject;
};
}
var age = "room";
var stu1 = new Student(
601,
"4组",
"王万琦",
18,
"千元村",
"徐燕",
"前段"
);
for (var k in stu1) {
console.log(stu1[k]); //遍历对象格式
}
// 对象赋值
stu1.hoppy = "打台球";
stu["hoppy"] = "打台球"; //推荐这种,因为底层转化原理为stu1.hoppy ------------>stu1['hoppy'] 这样少了编译转化
// 访问对象
stu1.age;
stu1.teacher;
stu["student"]; //推荐这种方式
// 更改对象属性值
stu1["adress"] = "上海市"; //如果对象中有这个属性,那么会替换这个值
stu1["hairNumber"] = "三根";//如果对象中没有这个值,那么会为对象增加这个属性
// new关键字的作用:
//1,创建了一个新对象stu1存放在堆里,与源对象互不干扰
//2,使其this指向这个新对象stu1(在如果在构造函数中不写this,那么这个this就不会指向这个对象,如果访问对象就会报错,因为新对象stu没有这个值)
//3,执行构造函数代码,为新对象赋予属性和方法
//4,返回这个stu1对象
</script>
js构造函数创建对象
最新推荐文章于 2023-03-12 08:00:00 发布