站长资讯网
最全最丰富的资讯网站

javascript中什么是类

在javascript中,类是一种用户定义类型,也称类类型,是一个具有相同属性和行为的群体的集合;从es6开始,可通过创建class关键字来定义一个类的模板,例“class 类名{}”。

javascript中什么是类

本教程操作环境: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);

效果展示:

hh 1 2 hh 3 4

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);

效果展示:

1 hh 1 2 1 hh 3 4

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高级教程】

赞(0)
分享到: 更多 (0)