12/9 新随笔
1.防抖
//防抖
function debounce(params) {
let timeout = null;
return function () {
clearTimeout(timeout);
timeout = setTimeout(() => {
params.apply(this, arguments);
}, 500);
};
}
function sayHi() {
console.log('successful');
}
var inp = document.getElementById('inp');
inp.addEventListener('input', debounce(sayHi));
2.节流
//节流
function throttle(fn) {
let canRun = true; // 通过闭包保存一个标记
return function () {
if (!canRun) return; // 在函数开头判断标记是否为true,不为true则return
canRun = false; // 立即设置为false
setTimeout(() => { // 将外部传入的函数的执行放在setTimeout中
fn.apply(this, arguments);
// 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。当定时器没有执行的时候标记永远是false,在开头被return掉
canRun = true;
}, 500);
};
}
function sayHi(e) {
console.log(e.target.innerWidth, e.target.innerHeight);
}
window.addEventListener('resize', throttle(sayHi));
3.call()/apply()
在JavaScript中,call和apply作用是一样的,都是为了改变某个函数运行时的上下文(context)而存在的,换句话说,就是为了改变函数体内部this的指向
function fruits(){}
fruits.prototype = {
color: "red",
say: function(){
console.log("My color is " + this.color);
}
};
var apple = new fruits;
apple.say(); //My color is red
function fruits(){}
fruits.prototype = {
color: "red",
say: function(){
console.log("My color is " + this.color);
}
};
var another = {
color: "yellow"
};
var apple = new fruits;
apple.say(); //My color is red
apple.say.call(another); //My color is yellow
apple.say.apply(another); //My color is yellow
区别:参数书写方式不同
call(thisObj, arg1, arg2, arg3, arg4);
apply(thisObj, [args]);
thisObj:call和apply第一个参数是一样的,该参数将替代Function类里面的this对象。
arg1,arg2…:是一个个的参数,
args:一个数组或类数组,是一个参数列表
function:
1.改变作用域
var name = "小白";
var obj = {
name: "小红"
};
function sayName() {
return this.name;
}
console.log(sayName.call(this)); //小白
console.log(sayName.call(obj)); //小红
2.实现继承
//实现js继承
//父类
function Person(name, height) {
this.sayInfo = function() {
return "姓名:" + name + ", 身高:" + height + ", 体重:" + this.weight;
}
}
//子类
function Chinese(name, height, weight) {
Person.call(this, name, height);
this.weight = weight;
this.nation = function() {
console.log("我是中国人");
}
}
//子类
function America(name, height, weight) {
Person.apply(this, [name, height]);
this.weight = weight;
}
let chiness = new Chinese("成龙", "178cm", "60kg");
console.log(chiness.sayInfo()); //姓名:成龙, 身高:178cm, 体重:60kg
let america = new America("jack", "180cm", "55kg");
console.log(america.sayInfo()); //姓名:jack, 身高:180cm, 体重:55kg