首页 > 其他分享 >七、ES6之class类

七、ES6之class类

时间:2023-10-15 17:05:54浏览次数:30  
标签:ES6 console log class stu Student sayHi

一、class基本语法

JavaScript 语言中,编写一个学生类,代码如下:(prototype可以个对象添加属性和方法)

function Student(stuno,stuname)
{
	this.stuno = stuno;
	this.stuname = stuname;
}
Student.prototype.stusex = "";
Student.prototype.sayHi = function()
{
	console.log("大家好,我是"+this.stuname+",我的学号是"+this.stuno+",性别:"+this.stusex);
}
var stu = new Student("001","孙悟空");
stu.stusex = "男";
//或
// var stu = new Student();
// stu.stuno = "001";
// stu.stuname = "孙悟空";
// stu.stusex = "男";
stu.sayHi(); //大家好,我是孙悟空,我的学号是001,性别:男

ES6提供了更接近传统语言的写法,引入了Class这个概念:

constructor为构造函数,当创建对象的时候自动调用:

class Student
{
	constructor(stuno,stuname) {
		this.stuno = stuno;
		this.stuname = stuname;
	}
	sayHi()
	{
		console.log("大家好,我是"+this.stuname+",我的学号是"+this.stuno);
	}
}
var stu = new Student("001","孙悟空");
//或
// var stu = new Student();
// stu.stuno = "001";
// stu.stuname = "孙悟空";
stu.sayHi();	//大家好,我是孙悟空,我的学号是001

注意:类的声明第一行除了class Student外,还可以如下写法:

let Student = class
let Student = class Student

二、类的属性和方法

实例属性和实例方法:

class Student
{
	stuno = "";
	stuname = "";
	sayHi()  //此处方法有的地方称为原型方法
	{
		console.log("大家好,我是"+this.stuname+",我的学号是"+this.stuno);
	}
}
var stu = new Student();
stu.stuno = "001";
stu.stuname = "孙悟空";
stu.sayHi();

静态属性和静态方法:

class Student
{
	stuno = "";
	stuname = "";
	static proName = "";  //专业名称
	static proIntroduce()
	{
		console.log("专业名称:"+Student.proName);
	}
	sayHi()
	{
		console.log("大家好,我是"+this.stuname+",我的学号是"+this.stuno);
	}
}
Student.proName = "计算机";
Student.proIntroduce();

三、实例方法的两种写法

方案一:(又称原型方法)

class Student
{
	sayHi()
	{
		console.log("hi!");
	}
}
let stu = new Student();
stu.sayHi();

等同于ES5中:

function Student(){			}
Student.prototype.sayHi=function()
{
	console.log("hi!");
}
var stu = new Student();
stu.sayHi();

方案二:

class Student
{
	constructor()
	{
		this.sayHi = function()
		{
			console.log("hi");
		}
	}
}
let stu = new Student();
stu.sayHi();

等同于ES5中:

function Student()
{
	this.sayHi = function()
	{
		console.log("hi");
	}
}
var stu = new Student();
stu.sayHi();

当两个方案冲突的时候,constructor里面的函数会覆盖外面的函数:

class Student
{
	sayHi()  //等同Student.prototype.sayHi=function(){...}
	{
		console.log("hi!");
	}
	constructor()
	{
		this.sayHi = function() //等同在function内部定义
		{
			console.log("hello!");
		}
	}
}
let stu = new Student();
stu.sayHi(); //hello!

等同于ES5中:

function Student()
{
	this.sayHi = function()
	{
		console.log("hello!");
	}
}
Student.prototype.sayHi=function()
{
	console.log("hi!");
}
var stu = new Student();
stu.sayHi(); //hello!

四、class属性封装

在类的内部可以使用get和set关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为。

class Student
{
	get stuAge(){
		return this._stuAge;
	}
	set stuAge(age)
	{
		if(age >= 18 && age <= 120)
			this._stuAge = age;
		else
		{
			this._stuAge = 18;
			console.log("年龄有错误,设置默认值18!");
		}
	}
}
let stu = new Student();
stu.stuAge = 17;   //年龄有错误,设置默认值18!
console.log(stu.stuAge); //18
//------------------------------------------------------------------------------
//注意:
//(1)在get和set后的属性名不能和函数里的取值和设置值的变量名相同(stuAge和_stuAge)
//(2)getter不可单独出现
//(3)getter与setter必须同级出现(不能一个在父类,一个在子类)

五、继承

通过 extends 实现类的继承。

//通过 extends 实现类的继承。
class People //父类
{
	name = "";
	sex = "";
	age = 0;
	sayHi()
	{
		console.log(`姓名:${this.name},性别:${this.sex},年龄:${this.age}`);
	}
}
class Student extends People  //子类继承父类,拥有父类的属性和方法
{
	
}
class Teacher extends People //子类继承父类,拥有父类的属性和方法
{
	salary = 0; //子类在父类基础上扩展一个属性
	sayHi() //子类在父类基础上重写父类方法
	{
		console.log(`姓名:${this.name},性别:${this.sex},年龄:${this.age},月薪:${this.salary}`);
	}
}
let stu = new Student();
stu.name = "孙悟空";
stu.sex = "男";
stu.age = 500;
stu.sayHi(); //姓名:孙悟空,性别:男,年龄:500

let tc = new Teacher();
tc.name = "唐僧";
tc.sex = "男";
tc.age = 100;
tc.salary = 6000;
tc.sayHi(); //姓名:唐僧,性别:男,年龄:100,月薪:6000

六、继承和构造方法

子类通过super()调用父类构造方法:

class People
{
	constructor(name,sex,age)
	{
		this.name = name;
		this.sex = sex;
		this.age = age;
	}
	sayHi()
	{
		console.log(`姓名:${this.name},性别:${this.sex},年龄:${this.age}`);
	}
}
class Student extends People
{
	constructor(name,sex,age)
	{
		super(name,sex,age);
	}
}
class Teacher extends People
{
	constructor(name,sex,age,salary)
	{
		super(name,sex,age);
		this.salary = salary;
	}
	sayHi()
	{
		console.log(`姓名:${this.name},性别:${this.sex},年龄:${this.age},月薪:${this.salary}`);
	}
}
let stu = new Student("孙悟空","男",500);
stu.sayHi(); //姓名:孙悟空,性别:男,年龄:500

let tc = new Teacher("唐僧","男",100,6000);
tc.sayHi();	//姓名:唐僧,性别:男,年龄:100,月薪:6000
//------------------------------------------------
//注意:
//(1)子类 constructor 方法中必须有 super ,且必须出现在 this 之前。
//(2)调用父类构造函数,只能出现在子类的构造函数。
//	例如在sayHi()中调用super就会报错;

super 作为对象的使用:


技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!

开源库地址,欢迎Star点亮:

GitHub:https://github.com/ITMingliang

Gitee:   https://gitee.com/mingliang_it

GitLab: https://gitlab.com/ITMingliang


建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。

七、ES6之class类_父类

标签:ES6,console,log,class,stu,Student,sayHi
From: https://blog.51cto.com/u_13096216/7872605

相关文章

  • Test class should have exactly one public zero-argument constructor(测试类应该只
    在练习重写equals方法时写测试方法遇到这个问题先放报错代码:publicclassOrder{intorderId;StringorderName;publicintgetOrderId(){returnorderId;}publicvoidsetOrderId(intorderId){this.orderId=orderId;}......
  • jsoup获取指定class名称的标签
      publicvoidloadHtmlFile(StringhtmlFilePath){try{Documentdoc=Jsoup.parse(newFile(htmlFilePath),"utf-8");Elementsdivs=doc.select("div.hop1");for(Elementdiv:divs){......
  • 论文阅读:CLIP2Point: Transfer CLIP to Point Cloud Classification with Image-Depth
    CLIP2Point:TransferCLIPtoPointCloudClassificationwithImage-DepthPre-TrainingCLIP2Point:通过图像深度预训练将CLIP传输到点云分类  ICCV2023摘要由于训练数据有限,3D视觉和语言的预训练仍在开发中。最近的工作尝试将视觉语言(V-L)预训练方法转移到3D视觉。然而,3D......
  • elasticsearch通过Java class类的@Setting和@Mapping来定义索引index
    今天就来和大家讲讲如何将es索引中的mapping和setting在索引index和class联系起来,其实在这个问题也困扰我好久了,一直没有解决,在elasticsearch7.x版本的时候貌似好像可以用request在程序中来建立索引,像Stringindex=“{“mapping”:...}”之类的操作,干起来比较复杂,在elasticsear......
  • GDCPC2023 L Classic Problem
    洛谷传送门CF传送门对于一个点\(x\),若\(\existsi,u_i=x\lorv_i=x\),则称\(x\)为特殊点,否则为一般点。首先发现,对于极长的一段\([l,r]\)满足\(l\simr\)均为一般点,那么可以连边\((l,l+1),(l+1,l+2),\ldots,(r-1,r)\),然后把\([l,r]\)缩成一......
  • 类里面静态方法(@staticmethod),类方法(@classmethod)和实例方法(self)的使用与区别
    前言python类里面常用的方法有3个:静态方法(@staticmethod),类方法(@classmethod)和实例方法(self)本篇讲解这3种方法在使用上有什么区别。函数先从函数说起,方法跟函数是有区别的,经常有人容易混淆,函数定义是def关键字定义(外面没class)deffun():a="hello"returna#......
  • 2024版Lightroom Classic13.0版本免激活版更新及资源
    2023年10月10日,Adobe又更新了LightroomClassic,当前最新的版本为13.0版本,本次更新最重磅的功能是使用人工智能AI来处理以前需要昂贵的镜头才能出来的模糊效果。LightroomClassic13.0版本使用了人工智能驱动的镜头模糊模糊背景或前景,轻松增加图像的深度。无需投资昂贵的镜头即可实......
  • 为什么我们需要不断的开发不同的机器学习模型 —— Do we Need Hundreds of Classifie
        ==========================================  论文:《DoweNeedHundredsofClassifierstoSolveRealWorldClassificationProblems?》  论文地址:https://jmlr.org/papers/volume15/delgado14a/delgado14a.pdf        =========......
  • java.lang.ClassNotFoundException org.apache.ibatis.io.Resources问题的解决
    问题描述时隔好久,再次使用mybatis框架写管理系统,运行时出现了这个问题;问题解决我看着我也导入了相关的依赖,然后就发现,原来是没有放入到libaray里面,只需要这么做就能搞定啦:打开项目里面的这里:将右边的需要的包双击即可加入进去啦!再次运行就不会报错啦~~......
  • [CF1285F]Classical?
    F-Classical?考虑先加上\(gcd(a_i,a_j)=1\)的限制从大到小扫集合里的数,若扫到数\(x\)发现存在\(y>x\)且\(gcd(x,y)=1\),则所有\(x<t<y\)的\(t\)都不会再对答案有贡献了,因此使用栈存储扫过的元素,当扫到\(x\)时,只要栈中有与\(x\)互质的数就弹栈,并与\(x\)更新答案那么如何快速判......