ES6类相关知识与继承

9 篇文章 0 订阅

传统构造函数的问题

  1. 属性与原型方法定义相分离,降低了可读性
  2. 原型成员可以被枚举
  3. 默认情况下,构造函数仍然可以被当做普通函数使用

类的基本使用

class Person  {
	constructor(name, age, sex) {
		this.name = name;
		this.age = age;
		this.sex = sex;
	}
	say(words) {
		console.log(words);
	}
}
let p = new Person("张三", 18, "男");
p.say("Hello");

类的特点

  1. 类声明不会被提升,与let和const一样,存在暂时性死区
  2. 类中的所有代码均在严格模式下执行
  3. 类的所有方法都是不可枚举的
  4. 类的所有方法都无法被当做构造函数使用
  5. 类的构造器必须使用new来调用

类的其他书写方式

可计算属性名
const prop1 = "name";
const prop2 = "say";
class Person {
	constructor(name) {
		this[prop1] = name;
	}
	[prop2](some) {
		console.log("do something " + some);
	}
}
const a = new Person("张三");
console.log(a[prop1]);
a[prop2]("hello");
getter与setter
class Person {
	constructor(name) {
		this.name = name;
	}
	get name() {
		return "我叫: " + this._name
	}
	set name(val) {
		if (typeof val !== "string") {
			throw new TypeError("get error type of value: \"name\" ")
		}
		this._name = val
	}
}
const a = new Person("张三");
console.log(a.name); //"我叫: 张三"
静态成员
class Test{
	static a = 10;
	static say() {
		console.log("123");
	}
}
let demo = new Test();
console.log(demo.a); //undefined
console.log(Test.a); // 10
demo.say(); //demo.say is not a function
Test.say(); //"123"
字段初始化器
class Test {
	a = 10;
	b = 20;
}
let demo = new Test();
demo.a; //10
demo.b; //20

类的继承

class Person {
	constructor(name, age, sex) {
		if (new.target === Person) {
			throw new Error("You shouldn't create it directly, use it's child classs")
		}
		this.name = name;
		this.age = age;
		this.sex = sex;
	}
	print() {
		console.log(`name: ${this.name}`);
		console.log(`age: ${this.age}`);
		console.log(`sex: ${this.sex}`);
	}
}

class Man extends Person {
	constructor(name, age) {
		super(name, age, "男"); //子类存在constructor函数 第一行必须调用super
		this.loves = "游戏"; //子类自身的属性, '游戏'可以作为参数传入
	}
	print() { //重复定义与父类相同的函数,在调用时会调用子类定义的函数
		super.print(); //调用父类的函数
		console.log(`loves: ${this.loves}`); //子类函数的独特打印
	}
}

let man = new Man("张三", 18);
man.print();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

合法的咸鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值