面試總結: 閉包相關問題與繼承相關的問題
一、閉包
閉包的概念:就是能夠讀取其他函式內部變數的函式
閉包的用處:1.讀取函式內部的變數2.讓這些變數的值始終儲存在記憶體中
閉包的缺點:1.造成記憶體的洩露。
二、繼承
1.原型鏈繼承2.借用建構函式繼承3.組合繼承4.原形式繼承5.寄生式繼承6.寄生組合式繼承
借用建構函式
思想:在子型別建構函式的內部呼叫超型別建構函式
如:function SuperType(name){
this.name=name;
}
function SubType() {
SperType.call(this,"zhanghuan") //核心
this.age=29
}
var instance=new SubType();
alert(instance.name) //"zhanghuan"
alert(instance.age) //29
組合繼承
思路:使用原型鏈實現對原型屬性和方法的繼承,而通過借用建構函式來實現對例項屬性的繼承
如:function SuperType (name){
this.name=name;
this.colors=["red","blue","green"]
}
SuperType.prototype.sayName=function (){
alert(this.name)
}
function SubType(name,age){
SuperType.call(this,name); //核心
this.age=age;
}
SubType.prototype=new SuperType(); //核心
SubType.prototype.constructor=SubType;
SubType.prototype.sayAge=function () {
alter(this.age)
}
var instance1=new SubType("zhanghuan",23);
instance1.colors.push("black");
alert(instance1.colors) //"red","blue","green","black"
instance1.sayName(); //zhanghuan
instance1.sayAge(); 23
var instance2=new SubType("Greg",29)
alert(instance2.colors) //"red" ,"blue","green"
instance2.sayName() //Greg
instance2.sayAge() 29