❓有任何疑问都可以私信我解答
⚡️仓库地址:https://gitee.com/super_li_yu/jsexamdemo
📌每天4道Js手写题,打卡第二天。
😛建议关注,持续更新。
✒️今天重点:继承,方法有点多,好好消化。
/**
* 手写防抖案例
* 防抖:多次执行变成一次执行
* fn是用户传入需要防抖的函数
* delay是等待时间,这里设置为100毫秒
*/
function fangdou(fn, delay = 100) {
//缓存一个定时器id
let timer = 0;
return function (...args) {
/**
* 这里返回的函数就是每次用户实际调用的防抖函数
* 如果已经设定过定时器了,就清空上一次的定时器,开始一个新的定时器,延迟执行用户传入的方法。
*/
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, args);
}, delay)
}
}
这里一共总结了5种继承方法
/**
* 继承
* 1. 原型链继承
* 2. 使用构造函数实现继承
* 3. 组合继承
* 4. 寄生式组合继承
* 5. class实现继承
*/
// 1. 原型链实现继承
function Father() {
this.name = '父亲'
this.age = 45
this.location = 'xxx公司'
}
Father.prototype.gotoWork = function () {
return this.location
}
function Son() { }
Son.prototype = new Father()
//实例化一个对象试试
var son1 = new Son()
son1.name = '孩子',
son1.age = 18,
son1.location = 'xxx学校',
console.log(son1)
// 2. 使用构造函数实现继承
function Animal(name) {
this.name = name
this.ageName = function () {
return this.name;
}
}
function Dog(name) {
Animal.call(this, name)
}
//实例化一个对象试试
var dog = new Dog('Tom')
console.log(dog)
// 3. 组合继承
function Fish(name) {
this.name = name;
this.color = 'red';
}
Fish.prototype.getColor = function () {
return this.color;
}
function SmallFish(name, color) {
Fish.call(this, name);
this.color = color;
}
SmallFish.prototype = new Fish();
SmallFish.prototype.constructor = SmallFish
//实例化一个对象看看
var smallfish1 = new SmallFish('尼牟', 'blue');
console.log(smallfish1)
//4.寄生式组合继承
function Ikun(name) {
this.name = name;
this.age = 25;
}
Ikun.prototype.getAge = function () {
return this.age;
}
function People(name, age) {
Ikun.call(this, name);
this.age = age;
}
People.prototype = Object.create(Ikun.prototype);
People.prototype.constructor = People;
//实例化一个对象看看
var kunkun = new People('爱坤', 17);
console.log(kunkun)
//5.类实现继承
class Car {
constructor() {
this.name = '汽车'
this.color = 'red'
}
getColor() {
return this.color;
}
}
class Ferriari extends Car {
constructor(name, color) {
super(name);
this.color = color;
}
}
//写一个实例看看
var fer = new Ferriari('法拉利', 'blue')
console.log(fer);