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

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
什么是类
在面向对象编程中,类(class)是对象(object)的模板,定义了同一组对象(又称"实例")共有的属性和方法。类是一种用户定义的引用数据类型,也称类类型。
我们可以理解类是一个具有相同属性和行为的群体的集合。
立即学习“Java免费学习笔记(深入)”;
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高级教程】
以上就是javascript中什么是类的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号