您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

javascript面向对象之一 定义类_js面向对象

2024/12/22 8:37:19发布34次查看
javascript中的类是用函数function表示的,如下:
复制代码 代码如下:
function student()
{
//定义类student中的字段,并赋予初值,但此字段的访问权限是public
this.studentno = 's001';
this.studentname = '小明';
this.sex = '男';
//定义类student中的方法updatestudentname ,用于修改studentname 值
this.updatestudentname = function(studentname)
{
this.studentname = studentname;
}
}
//如上代码便已定义了一个student类,并包含studentno ,
//studentname ,sex 3个字段,方法 updatestudentname. //然后调用updatestudentname 来修改studentname 的值,代码如下:
s.updatestudentname('小强');
alert('学号:'+s.studentno);
alert('姓名:'+s.studentname);
alert('性别:'+s.sex);
//再显示结果,学号和性别自然是不会改变的啦,结果如下:
学号:s001
姓名:小强
性别:男
//未调用updatestudentname 方法之前显示出学号,姓名,性别的值分别为:
学号:s001
姓名:小明
性别:男
//下面将进行调用,代码如下:
复制代码 代码如下:
var s = new student(); //创建student类的对象
alert('学号:'+s.studentno);
alert('姓名:'+s.studentname);
alert('性别:'+s.sex);
上面的function中已经设置好了具体的值,其实在实际应用中都是后面赋值的。例如
[ctrl+a 全选 注:如需引入外部js需刷新才能执行]
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product