最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

ES6中类和对象的代码示例

来源:动视网 责编:小采 时间:2020-11-27 19:29:22
文档

ES6中类和对象的代码示例

ES6中类和对象的代码示例:本篇文章给大家带来的内容是关于ES6中类和对象的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。1.基本定义和生成实例{ class Parent { constructor(name = 'haha') { this.name = name; } }
推荐度:
导读ES6中类和对象的代码示例:本篇文章给大家带来的内容是关于ES6中类和对象的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。1.基本定义和生成实例{ class Parent { constructor(name = 'haha') { this.name = name; } }


本篇文章给大家带来的内容是关于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中类和对象的代码示例

ES6中类和对象的代码示例:本篇文章给大家带来的内容是关于ES6中类和对象的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。1.基本定义和生成实例{ class Parent { constructor(name = 'haha') { this.name = name; } }
推荐度:
标签: 代码 对象 示例
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top