|
|
1.创建类和实例
class 类名{ //类名后不加()
... //类体
}
创建类后要实例化对象。使用new:
var 对象名 = new 类名()
2.类的构造函数
//创建类
class Person{
//定义构造函数
constructor(name,sex,age){
this.name = name;
this.sex= sex;
this.age= age;
}
}
//创建实例对象
var p = new Person("Tom","男",18)
console.log(p.name); // Tom
console.log(p.sex); // 男
console.log(p.age); // 20
3.在类中添加方法
//创建类
class Person{
//定义构造函数
constructor(name,sex,age){
this.name = name;
this.sex= sex;
this.age= age;
}
//添加show()方法
show(){
alert("姓名:" + this.name + "性别:" + this.sex + "年龄:" + this.age);
}
//创建实例对象
var p = new Person("Tom","男",18)
p.show()//调用show()方法
4.类的继承
//创建父类
class A{
//定义构造函数
constructor(name){
this.name = name;
}
showA(){
return "商品类型:" + this.name;
}
}
//创建子类
class Brand extends A{
//定义构造函数
constructor(name,bname){
super(name);
this.bname= bname;
}
show(){
return this.showA() + "<br/>商品品牌:" + this.bname;
}
}
var b = new Brand("手机","OPPO")
console.log(b.show);
5.静态成员
class Dog{
//静态成员
static type = "柯基";
static clolor = "黄色";
static show()= {
return "狗的价格:60"
}
//通过类名调用成员
document.write("" + Dog.type);
document.write("" + Dog.clolor );
document.write("" + Dog.show);
}
|
|