Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 18:10:51
Original
910 people have browsed it

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需刷新才能执行]
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!