ES6 类的完美继承 extends

class a {

constructor(x, y){

this.x = x;

this.y = y;

}

static print(){

console.log(‘打印中…’);

}

}

// b类继承a类

class b extends a{

constructor(x, y, z){

super(x, y);

this.z = z;

}

}

let c = new b();

b.print();

Object.getPrototypeOf(b) === a

  • super:调用父类的constructor里面的属性和方法(必须调用一次)

  • 父类的静态方法,也会被子类继承

  • 在子类使用this前必须先调用一次super父类

  • Object.getPrototypeOf方法可以用来从子类上获取父类

回到顶部 目录

super关键字


super实际就是:a.prototype.constructor.call(this)

class A {

constructor() {

console.log(new.target.name);

}

}

class B extends A {

constructor() {

super();

}

}

new A() // A

new B() // B

  • super()内部的this指向的调用者(子类)

  • super只能放在子类的constructor方法中,不然就报错

  • 如果super做为对象,在静态方法中,这时的super指向父类,而不是父类的原型

  • 类的方法就是静态方法带static的方法

  • 类继承中:静态方法对静态方法,普通方法对普通方法(super所在的地方)

  • 由于super使得this指向B的实例,所以super.valueOf()返回的是一个B的实例

类的prototype属性和__proto__属性


  • 子类的__proto__属性,表示构造函数的继承,总是指向父类的

  • 子类的prototype属性的__proto__属性,表示方法的继承,总是指向父类的prototype属性

class A {}

class B extends A {}

console.log(B.proto) // class A {}

console.log(B.prototype.proto == A.prototype) // true

回到顶部 目录

重写类的继承

class A {}

class B {}

// B的实例继承A的实例

Object.setPrototypeOf(B.prototype, A.prototype);

// B继承A的静态属性

Object.setPrototypeOf(B, A);

// Object.setPrototypeOf实现方法

Object.setPrototypeOf = function (obj, proto){

obj.protr = proto;

return obj;

}

原生构造函数的继承


ECMAScript的原生构造函数有:

  • Boolean()

  • Number()

  • String()

  • Array()

  • Date()

  • Function()

  • RegExp()

  • Error()

  • Object()

在ES6以前这些原生构造函数是无法继承的:

// 编写一个myArray继承Aarry的方法

常用的JavaScript设计模式

  • 单体模式

  • 工厂模式

  • 例模式

函数

  • 函数的定义

  • 局部变量和全局变量

  • 返回值

  • 匿名函数

  • 自运行函数

  • 闭包

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值