小编给大家分享一下ES6中类和对象的示例,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
1.基本定义和生成实例
{
class Parent {
constructor(name = 'haha') {
this.name = name;
}
}
let parent = new Parent('v');
console.log('构造函数和实例', parent); // Parent {name: "v"}
}
2.继承
{
class Parent {
constructor(name = 'haha') {
this.name = name;
}
}
class Child extends Parent {
}
console.log('继承', new Child()); // Child {name: "haha"}
}
3.继承传递参数
{
class Parent {
constructor(name = 'haha') {
this.name = name;
}
}
class Child extends Parent {
constructor(name = 'child') {
// super()方法,用来解决 继承怎么传递参数(怎么覆盖父类的参数)
// super的参数列表就是父类构造函数的参数列表,如果参数为空,就采用父类的参数默认值
super(name); // super必须放在构造函数第一行
this.type = 'child';
}
}
console.log('继承传递参数', new Child('hello')); // Child {name: "hello", type: "child"}
}
4.getter setter
{
class Parent {
constructor(name = 'haha') {
this.name = name;
}
// longName 是一个属性,不是方法
get longName() {
return 'lu-' + this.name;
}
// longName 是一个属性,不是方法
set longName(value) {
this.name = value;
}
}
let person = new Parent();
console.log('getter', person.longName); // lu-haha
person.longName = 'hello';
console.log('setter', person.longName); // lu-hello
}
5.静态方法
{
class Parent {
constructor(name = 'haha') {
this.name = name;
}
// static 关键字用来定义静态方法
static tell() {
console.log('do tell');
}
}
// 静态方法,直接通过类去调用,不是通过实例
Parent.tell(); // do tell
}
6.静态属性
{
class Parent {
constructor(name = 'haha') {
this.name = name;
}
}
// 直接在类上定义静态属性
Parent.type = 'test';
// 读取静态属性时,也是直接拿类读取
console.log(Parent.type); // test
}
看完了这篇文章,相信你对“ES6中类和对象的示例”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。