您好,欢迎访问一九零五行业门户网

javascript中什么是类

在javascript中,类是一种用户定义类型,也称类类型,是一个具有相同属性和行为的群体的集合;从es6开始,可通过创建class关键字来定义一个类的模板,例“class 类名{}”。
本教程操作环境:windows7系统、javascript1.8.5版、dell g3电脑。
什么是类
在面向对象编程中,类(class)是对象(object)的模板,定义了同一组对象(又称实例)共有的属性和方法。类是一种用户定义的引用数据类型,也称类类型。
我们可以理解类是一个具有相同属性和行为的群体的集合。
js 中的类
在es5之前,js中要表达一个类,要用一种叫做prototype-based的语法风格
function 士兵(id,hp){ this.id = id this.hp = hp } 士兵.prototype = { constructor:士兵() walk:function(){ } , shooting:function(){ } , }
在es6中,首次引入了类的概念,通过创建class关键字来定义一个类的模板。
1、在js中实现创建一个class
class number{}
2、实现class的构造方法、实例属性和实例方法
//构造方法class number{//实例属性constructor(id,age){//this指向当前事件this.id=id;this.age=age;}//实例方法num(){console.log("hh");}}//实例化对象var n1=new number("1","2");n1.num(1);console.log(n1.id);console.log(n1.age);var n2=new number("3","4");n2.num(2);console.log(n2.id);console.log(n2.age);
效果展示:
hh12hh34
3、class的静态属性和静态方法
//构造方法class number{//静态属性调用一个方法static ppp=1;//实例属性constructor(id,age){//this指向当前事件this.id=id;this.age=age;console.log(number.ppp)}//实例方法num(){console.log("hh");}}//实例化对象var n1=new number("1","2");n1.num(1);console.log(n1.id);console.log(n1.age);var n2=new number("3","4");n2.num(2);console.log(n2.id);console.log(n2.age);
效果展示:
1hh121hh34
4、类的继承
//父类class father{//构造方法不能被继承constructor(){console.log("我是父亲");this.name="father"}}//子类class son extend father{//执行子类构造方法之前必须先执行父类构造方法constructor(){super();//执行父类构造方法console.log("我是儿子")}}var son=new son;console.log(son.name)
效果展示:
我是父亲我是儿子father
【推荐学习:javascript高级教程】
以上就是javascript中什么是类的详细内容。
其它类似信息

推荐信息