JS的继承

本文回顾了ES6中的构造函数和原型链继承,并详细介绍了如何使用类的方式进行继承,包括`class`关键字、构造函数的`super`调用以及实例方法和静态方法的区别。重点讨论了通过`prototype`和`class`定义的继承机制,以及在实践中遇到的问题和解决方案。
摘要由CSDN通过智能技术生成

构造函数复习

function F1(name,age){
this.name = name;
this.age = age;
}
f1.prototype.method1 = function(){
console.log("helloworld");
}

原生的js是没有继承的标准语句的,那么我们就需要找一种方法来继承
我们在这之前还要学习一下constructor,

function F1(name,age)
{
this.name = name;
this.age = age;
}
var a = new F1("张三",18);
//F1.prototype.constructor = F1;//true
//prototype对象的constructor指向为F1函数
//a.constructor ===F1;//true
//a对象本身没有constructor的属性,a就会去找原型链去找构造函数

继承的进行曲

function A(m,b){
this.m = m;
this.b = b;
}
a.prototype.methods = function(){
console.log(11);
}
function B(m,b){
A.call(m,b);
this.values = 1;
}
B.prototype = Object.create(A.prototype);
//将A的原型生成一个匿名对象,是B的prototype指向该匿名对象,
//防止prototype的重复,
//因为关于对象”=“是将引用地址给赋值,而不是分配了一个独立的内存空间,
//于是将会导致B与A殊途同归,A,B最终成为同一个类即构造函数。
B.prototype.constructor = B;
//我们知道,当prototype改变,constructor指向也会改变,
//而我们还要调用它所以我们必须将constructor赋还给它

ES6继承方式

复习ES6的设置类的方式

class A{
constructor(a,b){
this.a = a;
this.b = b;
}
toString(){
console.log("A");
}
}

如阮一峰老师所说

class Point {
  constructor() {
    // ...
  }

  toString() {
    // ...
  }

  toValue() {
    // ...
  }
}

// 等同于

Point.prototype = {
  constructor() {},
  toString() {},
  toValue() {},
};
//1.class 中不存在变量提升
class Point {}
//2.class 中存在name属性
Point.name // "Point"
//箭头函数 var f = v => v;

class Logger {
  printName(name = 'there') {
    this.print(`Hello ${name}`);
  }

  print(text) {
    console.log(text);
  }
}

const logger = new Logger();
const { printName } = logger;
printName(); // TypeError: Cannot read property 'print' of undefined


出现上述问题的原因是因为this只指向刚开始构造时生成的对象,而this之后就会指向undefined

//一个比较简单的解决方法是,在构造方法中绑定this,
//这样就不会找不到print方法了。

class Logger {
  constructor() {
    this.printName = this.printName.bind(this);
  }

  // ...
}
//另一种解决方法是使用箭头函数。

class Obj {
  constructor() {
    this.getThis = () => this;
  }
}

const myObj = new Obj();
myObj.getThis() === myObj // true

继承

class B{
constructor(x,y){
this.x = x;
this.y = y;
}
}
class A extends B {
  constructor(x, y, color) {
    super(x, y); // 调用父类的constructor(x, y)
    this.color = color;
  }

  toString() {
    return this.color + ' ' + super.toString(); // 调用父类的toString()
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值