前端面试——继承(学习笔记)

ES5

要学会继承需要学会原型链,原型关系。总结一波手写继承:
父类

// 定义一个动物类
function Animal(name) {
    // 属性
    this.name = name || 'Animal';
    // 实例方法
    this.sleep = function () {
        console.log(this.name + '正在睡觉!');
    }
}

// 原型方法
Animal.prototype.eat = function (food) {
    console.log(this.name + '正在吃' + food);
};
//test
let animal = new Animal('lin');
animal.eat('apple');
animal.sleep();

子类实现继承,需要继承实例方法和属性,也要继承原型方法和属性:

//Sub
function Dog(name, color) {
    Animal.call(this, name);
    this.color = color;
}

(function () {
		//不此处有的用new Super(),不好,多用了一次父类构造函数
        Dog.prototype = Object.create(Animal.prototype);
        //Dog.prototype没有指定constructor属性,需要指回Dog
        Dog.prototype.constructor = Dog;
        Dog.prototype.sayColor = function () {
            console.log('the dog\'s color is ' + this.color);
        }
    }
)();

let haba = new Dog('Haba', 'black');
haba.sayColor();
console.log(haba.color);
console.log(haba.name);
haba.eat('meat');
haba.sleep();
不提倡的继承方法:
  • 实例继承
var instance = new Animal();
return instance;

实例是父类的实例,不是子类的实例;不支持多继承

  • 拷贝继承
var animal = new Animal();
for(var p in animal){
    Dog.prototype[p] = animal[p];
}

特点:支持多继承
缺点:效率较低,内存占用高(因为要拷贝父类的属性);无法获取父类不可枚举的方法(不可枚举方法,不能使用for in 访问到。

ES6

ES6中添加了类的概念——class,相应的继承——extend。

  • class的写法:
class Fish{	//定义了一个名字为Person的类
   constructor(color){	//constructor是一个构造方法,用来接收参数
       this.color = color;	//this代表的是实例对象
   }
   sayHellofish(){
       console.log(this.name+' say hello to every fishes!')
   }
}
var fish1=new Fish("fish1");
console.log(obj.say());	//fish1 say hello to every fishes!

构造函数的参数在constructor中接受
constructor方法是类的构造函数的默认方法,通过new命令生成对象实例时,自动调用该方法。
类定义的方法不加function不用分号,不加逗号

  • 继承
//es6方法
class Fish extends Animal{
    constructor(name, color){
    	//要先跟父类建立关联
        super(name);
        this.color = color;
    }
    sayHellofish(){
        console.log(this.name+' say hello to every fishes!')
    }
}
let fish1 = new Fish('fish1', 'yellow');
fish1.sleep();	//fish1正在睡觉!
fish1.eat('smallFish');	//fish1正在吃smallFish
fish1.sayHellofish();	//fish1 say hello to every fishes!

用super关键字调用父类构造函数,在constructor中引用父类,然后在设置子类属性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值