20200922赵鑫
学习总结
节流
节流,走字面上理解就是节约流量。比作水就话就是让水流的少一点,节约一点。对应到JS当中,就是在scroll事件和mousemove事件的时候,浏览器会很频繁的被触发,会导致对应的事件也会被很频繁的触发,这样就会使得浏览器资源消耗很大,此时就需要节流。
前面说过了,节流只是把水关小一点,同样,我们在JS中的节流就是让事件触发的不那么频繁。
function throttle(func, ms = 1000) {
let canRun = true
return function (...args) {
if (!canRun) return //如果是false 就终止
canRun = false
setTimeout(() => {
func.apply(this, args) //将this指向指向为事件触发时的this
canRun = true
}, ms)
}
}
// 测试
const task = () => { console.log('run task') }
const throttleTask = throttle(task, 1000)
window.addEventListener('mousemove', throttleTask)
去抖
去抖,用淘宝页面举例子,当我们在搜索输入词汇时,他会根据词汇自动的去获取后台与之相关联的数据。但是如果在我们没输入一个字符时都去响应,这也响应的泰国频繁且响应的数据都是无效的。那么我们就需要用到去抖,即在判断用户是否还要输入,如果不输入了再去发起请求。
function debounce(func, ms = 1000) {
let timer;
return function (...args) {
if (timer) {
clearTimeout(timer)
}
// console.log(timer)
timer = setTimeout(() => {
func.apply(this, args) //将this绑定为执行环境的this
}, ms)
}
}
// 测试
const task = () => { console.log('run task') }
const debounceTask = debounce(task, 1000)
window.addEventListener('mousemove', debounceTask)
JavaScript创建对象的方式汇总
1.构造函数创建
// 1.Object构造函数创建
var Obj = new Object();
Obj.name='saoge';
Obj.say=function(){
console.log(`我的名字是${this.name}`)
}
Obj.say();
2.使用对象字面量创建
//使用对象字面量创建
var Obj={
name:'saoge',
age:18,
say(){
console.log(`我的名字是${this.name},年龄${this.age}`)
}
}
Obj.say();
3.使用构造函数创建
//3.使用构造函数创建对象
function Obj(name,age){
this.name=name;
this.age=age;
this.say=function(){
console.log(`我的名字是${this.name},我的年龄是${this.age}`)
}
}
var objone = new Obj('saoge',18);
objone.say();
4.原型链创建对象
//4.原型链创建对象
function Obj(){}
Obj.prototype.name='saoge';
Obj.prototype.age=18;
Obj.prototype.say=function(){
console.log(`我的名字叫${this.name},我今年${this.age}岁`)
}
var objone=new Obj();
objone.say();
5.构造函数和原型混合使用
//5.构造函数和原型混合使用
function Obj(name){
this.name='name';
}
Obj.prototype.age=18;
Obj.prototype.say=function(){
console.log(`我叫${this.name},我今年${this.age}岁`)
}
var objone=new Obj('soage');
objone.say();
6.工厂模式
//6.工厂模式
//工厂模式使用较少,但是也需要了解
function createObj(name){
var obj = new Object();
obj.name = name;
obj.say=function(){
console.log(`我的名字叫${this.name}`)
}
return obj;
}
var objone = createObj('saoge');
objone.say();
7.class创建对象
// 7.class创建对象
class Obj{
constructor(name,age) {
this.name=name;
this.age=age;
}
say(){
console.log(`我的姓名是${this.name},我的年龄是${this.age}`)
}
}
var objone = new Obj('saoge',18);
objone.say();
学习心得
知识的积累在于总结,无论是学过的还是新学习的,去总结一次就可以彻底理解一次,记忆一次。
近期评论