es6 class定义类、单例类
ES6 class
1、有自己的构造函数
2、类中的一般方法会被统一放到原型上
3、使用extends继承
4、子类构造函数中super(父类属性)继承父类构造器,构造函数的参数也必须加上父类属性
5、使用继承后,子类的原型会指向父类的原型
6、子类同名方法调用时,会重载覆盖父类
7、__prototype__和__proto__区别
__proto__:
(1)浏览器厂商对每个对象添加的属性,指向对应的构造函数的prototype属性
(2)故子类的__proto__指向父类本身
(3)故子类的prototype的__proto__指向父类prototype属性
(4)故实例的__proto__属性的__proto__指向父类实例的__proto__
语法
class 类名{
参数=2; 参数会被绑定到this上
//构造器
constructor(参数)
{
(1)this.参数=参数; 通过this会绑定到实例上
(2)如果return出去一个对象,则实例的属性只有该对象,且实例不再是该类的实例
(3)构造函数中调用new target会返回当前类本身,子类super调用父类构造器中的new target会返回子类
}
//一般方法
方法名() 会绑定到实例的__proto__上,通过继承类的原型对象得来的
{
...
}
}
es6类创建私有方法:
方式一(提案中):
class X{
#x(){} 通过#前缀声明私有属性
}
方式二:
fucntion _fn(){};
class X{
fn(){
_fn.call(this);
}
}
方式三:
const fn=Symbol('xx');
class C{
[fn](){
...
}
}
将C导出,在其他模块中,因为无法获取Symbol值,所以获取不到C中的Symbol属性或方法
继承:
es6:
extends关键字,构造器中super调用
(1)extends:
会将类放在子类的原型上,所以子类也能调用父类的静态方法
Object.getPrototypeOf(子类)===父类; true
返回指定对象的原型
(2)super:
当做函数:
父类的构造方法
当做对象:
普通方法:指向父类原型对象,故只能调用一般方法,不能调用静态方法
静态方法:指向父类
es5:
将父类实例绑定到子类的原型对象上
function F(){
this.type = 'pare';
}
F.prototype.fn = () => { 实例将会继承类原型上的属性
console.log('fff');
}
function Z() {
this.name = 'z';
}
Z.prototype = new F();
继承原生构造函数:
原生构造函数:Object、Boolean、Array、Error、Number、String、Date、Function、RegExp
es5:无法继承原生构造函数
es6:
class X extends Array{
constructor(...args){
super(...args);
}
}
创建只能继承,不能实现的父类:
class F{
constructor(){
if(new target===F){
throw new Error('xx')
}
}
}
class Z{
constructor(){
super();
}
}
const z=new Z();
单例类:
export default class Sc{
static instance = null;
static Instance() {
if (!this.instance) {
this.instance = new Sc()
}
return this.instance
}
}
代码示例:
<html ng-app='app' ng-controller='main' >
<head>
<meta charset="utf-8">
<meta name='viewport' content='width=device-width,user-scalable=no,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0'>
<script src='jq/jquery-3.4.1.js'></script>
<style>
</style>
</head>
<body >
<script>
class Person
{
//类的构造方法
constructor(name,age)
{
this.name=name;
this.age=age;
}
//类的一般方法
show()
{
console.log(this.name);
}
}
//子类
class Jeff extends Person{
constructor(name,age,address){
super(name,age);//调用父类的构造方法
this.address=address;
}
show(){
console.log(this.address+this.name);
}
}
let person=new Person('jeff',18);
let jeff=new Jeff('jim',18,'where');
console.log(jeff);
jeff.show();
</script>
</body>
</html>
还没有评论,来说两句吧...