通过原型链的方式继承
通过实例化一个构造函数,使字类的原型指向父类的实例,字类就可以调用到父类的属性和方法
function Parent() {
this.parentName = '父亲';
this.getParentName = function () {
console.log("parent name is: %s", this.parentName);
return this.parentName;
}
}
function Child() {
this.childName = '子类';
this.getChildName = function () {
console.log("child name is: %s", this.childName);
return this.childName;
}
}
Child.prototype = new Parent();
function yxExtend() {
let childOne = new Child();
childOne.getParentName();
childOne.getChildName();
}
借用构造函数继承 call/apply函数
call/apply函数 能够改变函数的this指针
function Book(name, color) {
this.pages = 50;
this.name = name
this.color = color;
this.showBook = function () {
console.log("name of book: %s", this.name);
console.log("color of book: %s", this.color);
}
}
function RedBook(name, color) {
Book.call(this, name, color);
this.value = 60;
}
function gzExtend() {
var redBook = new RedBook("小红书", "红色");
redBook.showBook();
console.log("借用构造函数继承 call/apply函数, 打印结果:");
console.log(redBook);
}
class方式的继承 ES6以后的写法
class+extends+super
继承父实例属性:写在父的constructor中,子使用super访问
继承父实例方法:写在父类体中,子实例对象.方法名
继承静态方法、静态属性:使用static声明,子构造函数.静态方法名/静态属性名
注:只有在ES6中是这样创建类,给类做继承的
class Car{
constructor(name, color){
this.name = name;
this.color = color;
this.powertype = "汽油";
console.log("父类构造器");
}
sayCarName(){
console.log("this car name is: %s", this.name);
}
static manufacturer = "默认厂商";
static carDistinguish(carOne){
console.log("识别%s是否为 Car", carOne.name);
console.log(carOne instanceof Car);
return carOne instanceof Car;
}
}
class Benz extends Car{
constructor(name, color, length){
super(name, color);
console.log("子类构造器");
this.length = length;
this.capacity = 4; //默认载客量
}
static maxSpeed = 200;
static benzDistinguish(carOne){
console.log("识别%s是否为 Benz", carOne.name);
console.log(carOne instanceof Benz);
return carOne instanceof Benz;
}
}
function clExtend() {
var one = new Car("比亚迪", "white");
console.log(one);
var two = new Benz("奔驰e330", "black");
two.sayCarName();
console.log(two);
console.log("Car.carDistinguish(one) is:");
Car.carDistinguish(one);
console.log("Car.carDistinguish(two) is:");
Car.carDistinguish(two);
console.log("Benz.carDistinguish(one) is:");
Benz.benzDistinguish(one);
console.log("Benz.carDistinguish(two) is:");
Benz.benzDistinguish(two);
}
控制台的打印结果: