百度到的很多內(nèi)容都是類似這樣的:
靜態(tài)方法
function Afun(){}
Afun.sayA=function(){
console.log("Hello World A!");
}
實(shí)例方法
function Bfun(){}
Bfun.prototype.sayB=function(){
console.log("Hello World B!");
}
var b=new Bfun();
b.sayB();//輸出Hello World B!
然后就很少有然后了绰更,今天突然看到靜態(tài)方法與實(shí)例方法這個詞之后惰帽,于是有了這篇文章,讓我們看看還有什么其他不同与殃。
上邊提到靜態(tài)方法是直接通過屬性添加的方法,實(shí)例方法是添加給實(shí)例化對象的方法捏肢。
function Afun(){}
Afun.sayA=function(){
console.log("Hello World A!",this);
}
Afun.sayA() //輸出Hello World A! ? Afun(){}
function Bfun(){}
Bfun.prototype.sayB=function(){
console.log("Hello World B!",this);
}
var b=new Bfun();
b.sayB();//輸出Hello World B! Bfun {}
不難看出奈籽,靜態(tài)方法中的this指向的是構(gòu)造函數(shù)本身,而實(shí)例方法中的this指向的是實(shí)例化對象鸵赫。
function Bfun(){
this.sayC=function(){
console.log("Hello World C!",this)
}
}
Bfun.sayA=function(){
console.log("Hello World A!");
}
Bfun.prototype.sayB=function(){
console.log("Hello World B!");
}
var b=new Bfun();
Bfun.sayB(); // Uncaught TypeError: Bfun.sayB is not a function
Bfun.sayC(); // Uncaught TypeError: Bfun.sayC is not a function
b.sayA(); // Uncaught TypeError: b.sayA is not a function
b.sayC(); // Hello World C! Bfun {sayC: ?}
這里要表達(dá)的是實(shí)例方法不能通過構(gòu)造函數(shù)直接調(diào)用衣屏,而靜態(tài)方法也不能通過實(shí)例調(diào)用。定義在構(gòu)造函數(shù)內(nèi)部的形式也是實(shí)例方法辩棒,表現(xiàn)與原型鏈添加的方式一致狼忱,但并不推薦這種寫法。
此外如果是通過原型鏈進(jìn)行的繼承一睁,那么也不會繼承靜態(tài)方法
有說法靜態(tài)方法和實(shí)例方法對內(nèi)存的分配也不同钻弄,如果實(shí)例方法是通過原型鏈添加的話,我覺得沒啥不同(手動狗頭)者吁。還望指教窘俺。