JavaScript学习笔记 .10——构造函数的继承范式

152 阅读2分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

有了前面几节的知识,老实说各位完全可以自己掌握Javascript的继承方式了。

这下我来贴一个比较常用的构造函数的继承范式。

1. 编写基构造函数:

function Person(name,gender,age){
  this.name = name;
  this.gender = gender;
  this.age = age;
};
Person.prototype.doSomething=function(thing){
  console.log("now "+this.name+" is doing "+thing+" , it is seems fun!");
};
Person.prototype.bio=function(){//个人简历
  console.log("My name is "+this.name);
};

编写范式:

  • 成员属性写函数体内
  • 成员函数写函数的原型prototype内(写在了函数的外面)

这样写是不是有C++的感觉了?成员属性写内部,成员方法定义写外部。

2. 成员属性的继承

编写子构造函数:

function BUAAer(name,gender,age,major){
  Person.call(this,name,gender,age);
  this.major = major;
};

编写范式:

  • 使用基函数的call函数指定基函数执行时的this指向(指向new的实例)

  • 内部编写其他成员属性

  • 此时基函数的成员已经继承给子函数

    有一个问题:设函数A(){this.a='abc'};,那么在直接调用A()而不是使用new时,a变量定义在了哪里?
    在控制台中执行A函数,再输入a,发现输出了"abc"字符串。
    答案是:定义了一个
    全局变量
    a,因为this不指向任何自行创建的实例。

3. 成员方法的继承

BUAAer.prototype=Object.create(Person.prototype);
Object.defineProperty(BUAAer.prototype, 'constructor', {
  value: BUAAer,
  enumerable: false, // so that it does not appear in 'for in' loop
  writable: true });
BUAAer.prototype.bio(){
  console.log("My name is "+this.name+", a BUAA student!");
}

编写范式:

  • 使用create方法,摒弃子函数原来的prototype,构造一个新的prototype,其原型指向基函数Personprototype,使得可以继承基函数的方法。
  • 此时子函数的prototype空无一物,而一般都需要一个成员constructor作为指向自己的指针,故使用Object.defineProperty()创建。
  • 然后就可以创建子函数的方法了,并且也可以覆盖之前的。

至此,我们的原型的学习就告一段落了。