深浅拷贝,防抖节流,继承多态
深浅拷贝
浅拷贝是拷贝的地址
var obj={}; //obj=0x100;
a=obj; //a=0x100;
深拷贝是拷贝每一个值
var arr=[1,2]; //arr=0x100;
var b=[]; //b=0x200;
b[0]=arr[0]; //b[0]=1;
b[1]=arr[1]; //b[1]=2;
防抖
当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次;
如果设定时间到来之前,又触发了事件,就重新开始延时。
var ipt = document.querySelectorAll("input");
//让元素在键盘抬起的时候,向服务器发起请求,请求相关的数据
var timerid = null;
ipt[0].addEventListener('keyup', function () {
//清除定时器
if (timerid) {
clearTimeout(timerid);
}
timerid = setTimeout(function () {
console.log('向服务端请求数据.....ing');
}, 3000);
})
节流
指在 n 秒内连续触发事件只执行一次函数。
/**
* @desc 函数节流
* @param callback 函数
* @param time 延迟执行毫秒数
*/
function throttle(callback,time){
//假设:假设用户在既定时间内没有输入了
var tag = true; //因为用户有频繁的输入
return function(){
if(tag){ //如果用户真的有频繁输入的动作
tag = false; //禁止这种频繁的输入动作
setTimeout(function(){
callback();
tag = true;
},time);
}
}
}
继承
-
原型继承
让父类的实例作为子类的原型,将子类的原型构造器补充完整 (为了让子类继承方法)
<body>
<script>
//父类
function Person(){
}
//子类
function Student(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
//原型继承
Student.prototype = new Person();
Student.prototype.constructor = Student;
//实例化子类对象
var s1 = new Student("王五",25,"男");
console.log(s1); //Student {name: '王五', age: 25, sex: '男'}
</script>
</body>
-
使用构造函数方式继承
在子类当中去调用父类的构造函数(为了让子类继承属性)
<body>
<script>
//父类
function Person(){
this.name = name;
this.age = age;
this.sex = sex;
}
//子类
function Student(name,age,sex){
//使用构造函数方式继承
Person.call(this,name,age,sex);
}
//实例化子类对象
var s1 = new Student("王五",25,"男");
console.log(s1); //Student {name: '王五', age: 25, sex: '男'}
</script>
</body>
-
组合方式继承
原型继承方法,借用构造函数继承属性一起使用
<body>
<script>
//父类
function Person(){
this.name = name;
this.age = age;
this.sex = sex;
}
//子类
function Student(name,age,sex){
//使用构造函数方式继承
Person.call(this,name,age,sex);
}
//原型继承
Student.prototype = new Person();
Student.prototype.constructor = Student;
//实例化子类对象
var s1 = new Student("王五",25,"男");
console.log(s1); //Student {name: '王五', age: 25, sex: '男'}
</script>
</body>
多态
方法的重写和重载也是多态的一种体现
-
方法重载
同一个方法会根据参数的不同来执行不同的业务逻辑
<body>
<script>
//父类
function Person(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
Person.prototype.eat = function(num){
if(typeof num == "number"){
console.log('一天吃'+num+'顿');
}else{
console.log('今天吃了');
}
}
var p1 = new Person();
p1.eat(); //今天吃了
p1.eat(5); //一天吃5顿
</script>
</body>
-
方法重写
和父类同名方法功能不同,被称作方法重写
<body>
<script>
//父类
function Person(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
this.eat = function(){
console.log('吃了吗');
}
}
//子类
function Student(){
this.eat = function(){
console.log('吃了您嘞');
}
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
var s1 = new Student();
s1.eat(); //吃了您嘞
</script>
</body>

浙公网安备 33010602011771号