Classes in JavaScript are represented by functions, as follows:
function Student()
{
//Define the field in class Student and assign it an initial value, but the access permission of this field is public
this.studentNo = 's001';
this.studentName = 'Xiao Ming';
this.sex = 'Male';
//Define the method updateStudentName in the class Student, which is used to modify the studentName value
this.updateStudentName = function(studentName)
{
this.studentName = studentName;
}
}
//The above code has defined a Student class and contains studentNo,
// studentName, sex 3 fields, method updateStudentName. //Then call updateStudentName to modify the value of studentName. The code is as follows:
s.updateStudentName('Xiaoqiang');
alert('student number:' s.studentNo) ;
alert('Name:' s.studentName);
alert('Gender:' s.sex);
//Display the results again, the student number and gender will naturally not change. The results are as follows:
Student ID: s001
Name: Xiaoqiang
Gender: Male
//The values of student ID, name, and gender are displayed before the updateStudentName method is called:
Student ID :s001
Name: Xiao Ming
Gender: Male
//The following will be called, the code is as follows:
var s = new Student(); //Create an object of student class
alert('Student number:' s.studentNo);
alert( 'Name:' s.studentName);
alert('Gender:' s.sex);
The specific values have been set in the above function. In fact, in actual applications It is assigned later. For example
]<script>
function Student(studentNo,studentName,sex)
{
//定义类Student中的字段,并赋予初值,但此字段的访问权限是public
this.studentNo = studentNo;
this.studentName = studentName;
this.sex = sex;
//定义类Student中的方法updateStudentName ,用于修改studentName 值
this.updateStudentName = function(studentName)
{
this.studentName = studentName;
}
}
var s = new Student("001","小明","男"); //创建student类的对象
alert('学号:'+s.studentNo);
alert('姓名:'+s.studentName);
alert('性别:'+s.sex);
s.updateStudentName("脚本之家"); //修改名字
alert('学号:'+s.studentNo);
alert('姓名:'+s.studentName);
alert('性别:'+s.sex);
</script>