深淺拷貝,防抖節流,繼承多型
阿新 • • 發佈:2022-04-19
深淺拷貝
淺拷貝是拷貝的地址
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>