ES6-Class 记录
来源:互联网 发布:java获取当天0点时间 编辑:程序博客网 时间:2024/06/05 11:08
一. Class基础用法:
在ES6之前我们一般这样写
function Cat(name) { this.name = name; } Cat.prototype.sayName = function() { console.log("name: " + this.name); } var cat = new Cat('ZZ'); cat.sayName();
ES6引入Class后这个函数就可以这样写
class Cat { constructor(name) { this.name = name; } sayName() { console.log("name: " + this.name); } } var cat = new Cat('ZZ'); cat.sayName();
这样写有点感觉类似java中类的写法。
当你用 new 生成实例时 constructor方法就会自动调用,即使你没有定义方法 也会默认添加的
constructor方法被调用时就会接受传递的参数。
这里有两点需要注意:
1.
class Cat { constructor(name) { this.name = name; } sayName() { console.log("name: " + this.name); } } Cat();
这样写是会报错的 因为当你用Class时 必须用new声明实例
2.
var cat = new Cat("ZZ"); class Cat { constructor(name) { this.name = name; } sayName() { console.log("name: " + this.name); } }这样写也是会报错的( Cat is not defined) 因为 Class不存在变量提升了。
二. 继承:
继承的代码是这样的:
class animal { constructor(name) { this.name = name; } run() { console.log('name: ' + this.name + ' run run'); } } class Cat extends animal { constructor(name, age) { super(name); this.age = age; } sayName() { console.log("name: " + this.name + ' age: ' + this.age); } } var cat = new Cat("xiaoMing", 17); cat.run(); cat.sayName();
运行结果是:
name: xiaoMing run runname: xiaoMing age: 17
Class的继承通过extends 实现
然后在子类Cat中的 constructor 方法内 通过super 向父类传递参数
这里有两点需要注意
1 constructor 方法内必须写super 否则会报错
2.super之前使用this关键字是会报错的
像这样
this.age = age;super(name);
三.取值函数(getter)和存值函数(setter)
代码:
class Cat{ constructor() { } get age() { return this.num; } set age(num) { this.num = num; } } var cat = new Cat(); cat.age = 17; console.log('cat age: ' + cat.age);//17
四 Class静态方法(static)
当我将某个方法加上 static关键字时 这个方法就不会被实例继承,只能通过类来调用
这句话的意思用代码表示就是:
class animal { constructor(name) { this.name = name; } run() { console.log('name: ' + this.name + ' run run'); } static walk() { console.log('walk walk'); } } class Cat extends animal { constructor(name, age) { super(name, age); } } var cat = new Cat('xiaoMing', 17); cat.run(); cat.walk(); animal.walk(); Cat.walk();
这段代码在运行时就会报错 (cat.walk is not a function)
当把
cat.walk();注释掉就不会报错了.
仔细观看代码你会发现 父类和子类都可以调用这个被static修饰的 方法.
阅读全文
0 0
- ES6-Class 记录
- ES6--Class
- ES6 Class
- ES6--class
- ES6-class
- 【ES6】class
- ES6详解三:class
- ES6详解三:class
- ES6 Class 类
- javascript ES6之class
- 自学-ES6篇-Class
- es6中class学习
- ES6 class enum function
- 13、ES6 之class
- ES6 学习笔记 Class
- ES6 Class的用法
- es6中的class类
- es6中的class
- BZOJ 2223: [Coci 2009]PATULJCI 主席树
- ambari数据库分析-adminresource
- node.js学习笔记
- 多进程 VS 多线程
- Telnet命令检测远程主机上的端口是否开启
- ES6-Class 记录
- C Primer Plus 第9章 函数 编程练习
- OTT-TV网络电视EPG录制和EPG抓取解决方案
- 历届试题 打印十字图
- JavaScript Array的常用方法(二)
- 1953(简单)
- linux打包压缩命令
- JavaScript变量对象的深入
- 优先队列