当前位置:网站首页>ES6-class类
ES6-class类
2022-08-11 05:17:00 【前端小马】
概述:
在ES6中,class (类)作为对象的模板被引入,可以通过 class 关键字定义类。
class 的本质是 function。
它可以看作一个语法糖,让对象原型的写法更加清晰、更像面向对象编程的语法。
使用类:
class Father {
//static表示静态属性或方法
static name="小王"
static change(){
return "我是静态方法"
}
//constructor 方法是类的默认方法,创建类的实例化对象时被调用。
constructor(x, y) {
this.x = x;
this.y = y;
}
//原型方法
sum() {
return this.x + this.y;
}
}
var son=new Father(1,2)
console.log(typeof Father)//function ES6的类,完全可以看作构造函数的另一种写法。
console.log(son.sum())//3
console.log(son.__proto__==Father.prototype)//true
Father()//报错,类必须使用new调用,否则会报错
var a=Father()//报错,类必须使用new调用,否则会报错
console.log(son.name)//undefined
console.log(son.change())//报错,son.change is not a function
console.log(Father.name)//小王
console.log(Father.change())//我是静态方法
取值函数(getter)和存值函数(setter):
class Father {
get num() {
console.log("num被读取了")
return "2" //返回值就是num的值
}
set num(value){
console.log("num被修改了改成了"+value)
}
}
var son=new Father()
console.log(son.num)//num被读取了 2
son.num=1 //num被修改了改成了1
class继承:
class Father {
constructor(name,age){
this.name=name
this.age=age
}
call(){
return "打电话"
}
}
//子类继承父类——语法:class 子类 extends 父类
class Son extends Father{
constructor(name,age,height){
//super在子类的构造方法中调用父类的构造方法
super(name,age) //this操作必须放在super后面
this.height=height
}
play(){
console.log("玩游戏")
}
}
var son= new Son("小王",16,180)
console.log(son.name)//小王
console.log(son.call())//打电话
console.log(son.height)//180
边栏推荐
猜你喜欢
task06 PyTorch生态
Flask framework to study: the debug and configuration items
npm install 时报 npm ERR Cannot read properties of null (reading ‘pickAlgorithm‘)
使用Go语言开发的低代码应用引擎
(2) Construction of a real-time performance monitoring platform (Grafana+Prometheus+Jmeter)
【win10+cuda7.5+cudnn6.0安装caffe⑥】报错及处理方式
C语言——文件操作(2)文件的读写操作
【翻译】博客游戏项目Q1K3 – 制作
C语言——文件操作详解(1)
【win10+cuda7.5+cudnn6.0安装caffe④】安装pycaffe
随机推荐
RK3399上的Tengine实践笔记
Win下安装不同版本的MinGW(g++/gcc)以及对应clion编辑器的配置
Chapter 5 Loops and Relational Expressions
LeetCode1166.设计文件系统
(1) Construction of a real-time performance monitoring platform (Grafana+Influxdb+Jmeter)
C语言——程序的编译与执行、宏定义详解
Chapter 4 Composite Types-1
第4章 复合类型-1
【背包】采药题解
pytorch安装笔记——Pytorch在conda+CUDA10.2环境安装task01
Chapter 13 Class Inheritance-1
C语言——逆序输出字符串的函数实现
C语言版——通讯录进阶(文件版本)
08-JS对象、原型及原型链
全国青少年信息学奥林匹克联赛大纲
2021研究生数学建模D题,BP神经网络和卷积神经网络解题代码(基于pytorch)
【翻译】博客游戏项目Q1K3 – 制作
[转载]Verilog testbench总结
C语言的二维数组初始化的几种方式介绍(私藏大数组初始化方式)
数组的相关方法及使用