<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
/*********************************创建对象***********************************/
//方法一:
//创建学生对象
var student={
studentName:'黄裳',
age:'70',
speak:function(){
return '能说英语。';
}
}
//方法二:
var teacher=new Object();
teacher.teacherName='韩立';
teacher.age='2000';
teacher.speak=function(){
return '能斗法。';
}
//方法三:
//注意:
//1、推荐构造函数首字母大写;
//2、this表示当前对象;
//3、用构造函数创建对象要用new。
function CreateTeacher(teacherName,age){
this.teacherName=teacherName,
this.age=age,
this.fun=function(a){
return a;
}
}
var ct1=new CreateTeacher('zhangsan','20');
/*********************************获取对象属性***********************************/
//获取属性方法一:
console.log(student.age);
console.log(student.speak());
console.log(student.studentName);
//获取属性方法二:
console.log(teacher['age']);
console.log(teacher['teacherName']);
console.log(ct1.age);
console.log(ct1.teacherName);
console.log(ct1.fun('能工作'));
/*********************************遍历对象属性***********************************/
console.log('遍历对象属性');
for(k in student){
//属性名
console.log(k);
//属性值
console.log(ct1[k]);
}
</script>
</head>
<body>
</body>
</html>
JS创建及使用对象
猜你喜欢
转载自blog.csdn.net/qq_39706570/article/details/106755958
今日推荐
周排行