目录
一.类的定义和实例化
在JavaScript中没有声明类的关键字,也没有对类访问的权限控制,JavaScript中使用函数来定义类
1.类的定义
定义类的语法:
function className(){
}
例:
function student(){
this.name="myun";
this.age=22;
this.school="ybu";
this.like=function(){
alert("hello world, hello time");
}
}
2.类的实例化
在JavaScript中类的实例化使用关键字new,类的实例化即是创建对象
创建对象语法:
new className();
例:上面的student类
var student=new student();
student.like();
在JavaScript中还可以通过对象直接初始化对象,该方法不需要使用new关键字就可以生成实例:
var student={
name:"myun";
age:22
school:"ybu";
like:function(){
alert("hello world hello time");
}
/* 或者
student.like=function(){
alert("hello world hello time");
}
*/
}
二.访问和添加对象的属性和方法
属性是一个变量,用来表示一个对象的特征,方法是一个函数,用来表示对象的操作