一些语法块
防抖函数
"use-strict"
function debounce(func, delay) {
let timer
return function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
func.call(this, args)
}, delay)
}
}
节流函数
"use-strict"
function throttle(func, delay) {
let canRun = true
return function (...args) {
if (!canRun) {
return
}
canRun = false
setTimeout(() => {
func.call(this, args)
canRun = true
}, delay)
}
}
组合式继承
"use-strict"
function Parent(value) {
this.val = value
}
Parent.prototype.getValue = function () {
console.log(this.val)
}
function Child(value) {
Parent.call(this, value)
}
Child.prototype = new Parent()
const child = new Child("Child")
const parent = new Parent("Parent")
console.log(child instanceof Parent)
child.getValue()
parent.getValue()
组合寄生式继承
"use-strict";
function Parent(value) {
this.val = value;
}
Parent.prototype.getValue = function () {
console.log(this.val);
};
function Child(value) {
Parent.call(this, value);
}
Child.prototype = Object.create(Parent.prototype, {
constructor {
value Child,
writable true,
configurable true,
enumerable false,
},
});
const child = new Child("Child");
const parent = new Parent("Parent");
console.log(child instanceof Parent);
child.getValue();
parent.getValue();
实现New
操作符
"use-strict";
function myNew(Cons, ...args) {
let obj = {};
obj.__proto__ = Cons.prototype;
let res = Cons.call(obj, args);
return typeof res === "object" ? res obj;
}
function Person(value) {
this.name = value;
}
Person.prototype.getName = function () {
console.log(this.name);
return this.name;
};
const suyechun = myNew(Person, "syc");
suyechun.getName();
实现instance of
"use-strict"
function myInstanceof(left, right) {
let rightProto = right.prototype
let leftValue = left.__proto__
while (true) {
if (leftValue === null) {
return false
}
if (leftValue === rightProto) {
return true
}
leftValue = leftValue.__proto__
}
}
function Person(value) {
this.name = value
}
Person.prototype.getName = function () {
console.log(this.name)
return this.name
}
const suyechun = new Person("syc")
console.log(myInstanceof(suyechun, Person))
斐波那契数列
function* fibonacci() {
let [prev, curr] = [0, 1]
for (;;) {
yield curr
;[prev, curr] = [curr, prev + curr]
}
}
for (let n of fibonacci()) {
if (n > 1000) break
console.log(n)
}