1.面向對象編程
舉一個 例子說明一下:
面向對象思想: 貓.抓(老鼠)
面向過程思想: 抓.(貓,老鼠)
//面向對象
//定義貓(名字)
let Cat=function(name){
this.name=name;
}
//動作
Cat.prototype={
catch:function(someThing){
console.log(`${this.name}抓${someThing}`);
}
}
//創建一個貓對象
let daidai=new Cat('呆呆');
daidai.catch('老鼠');
//面向過程
let catch = function(who,someThing){
console.log(`${this.name}抓${someThing}`);
}
catch("daidai","老鼠")
雖然結果相同,但是不難發現面向對象更加的靈活,複用性和擴展性更加。因爲面向對象就是針對對象來進行執行某些動作。這些動作可以自定義擴展。
而面向過程是定義很多的動作,來指定誰來執行這個動作。
2.this
使用 JavaScript 開發的時候,很多開發者多多少少會被 this
的指向搞蒙圈,但是實際上,關於 this
的指向,記住最核心的一句話:哪個對象調用函數,函數裏面的this指向哪個對象。
下面分幾種情況談論下
1).普通函數調用
這個情況沒特殊意外,就是指向全局對象-window。var username='mayue'
function fn(){
alert(this.username);//mayue
}
fu();
//---------------
window.username='mayue'
function fn(){
alert(this.username);//mayue
}
fn();
//可以理解爲
//window.fn();
但是下面這種情況輸出的就會是undefined,因爲是let聲明,不會是window對象let username='mayue'
function fn(){
alert(this.username);//undefined
}
fn();
2).對象函數調用
那個函數調用,this就指向哪裏
3).構造函數調用
let TestClass=function(){
this.name='yuema';
}
let subClass=new TestClass();
subClass.name='mayue';
console.log(subClass.name);//mayue
let subClass1=new TestClass();
console.log(subClass1.name)//yuema
注意:在構造函數裏面返回一個對象,會直接返回這個對象,而不是執行構造函數後創建的對象
4).apply和call調用
apply和call簡單來說就是會改變傳入函數的this。
5).箭頭函數調用
let obj={
a:"mayue",
fn:function(){
setTimeout(()=>{console.log(this.a)});
}
};
obj.fn();//mayue
3.call和apply
call 和 apply 的作用,完全一樣,唯一的區別就是在參數上面。
call 接收的參數不固定,第一個參數是函數體內 this 的指向,第二個參數以下是依次傳入的參數。apply接收兩個參數,第一個參數也是函數體內 this 的指向。第二個參數是一個集合對象(數組或者類數組)
let obj1={
a:"mayue"
};
let obj2={
a:"yuema",
fn:function(){
alert(this.a);
}
}
obj2.fn.call(obj1);
call 和 apply 兩個主要用途就是
1.改變 this 的指向(把 this 從obj2 指向到obj1)
2.方法借用(obj1沒有 fn,只是借用obj2方法)