JS(十五)繼承模式,命名空間,對象枚舉(上)

寫在最前面

繼承的發展史

  • 傳統形式 –> 原型鏈
    • 過多的繼承了沒有用的屬性
  • 借用構造函數
    • 不能繼承借用構造函數的原型
    • 每次構造函數都要多走一個函數
  • 共享原型
    • 不能隨便改動自己的原型
  • 聖盃模式
原型鏈的繼承


A.prototype.name = "wu";
function A (){

}
var a = new A();

B.prototype = a;
function B (){

}
var b = new B();


C.prototype = b;
function C (){

}

var c = new C();
借用構造函數繼承

function Person(name,age,sex){
    this.name = name;
    this.age = age;
    this.sex = sex;
}

function Student(name,age,sex,grade){
    Person.call(this,name,age,sex);
    this.grade = grade;
}

var sutdent = new Student();

共享原型
Father.prototype.lastName = "tang"
function Father(){

}

function Son() {

}

Son.prototype = Father.prototype;

var son = new Son();
var father =  new Father();

//缺點不能隨便修改自己的原型

比如我在下面
Son.prototype.sex = "male";
son.sex//打印出"male";
father.sex = "male";
因爲他們兩個的原型指向了同一個地方;
聖盃模式
Father.prototype.lastName = "tang"
function Father(){

}

//我自己設置箇中間層
function F(){

}

function Son() {

}

F.prototype = Father.prototype;

Son.prototype = new F();

//設置成一箇中間層
//這樣子寫的好處就是son在自己的原型上面加東西
// 不會影響別的原型,因爲son的原型是new F(); new F的原型纔是Father.prototype
function inherit (Target,Origin){
    function F(){}
    F.protptype = Origin.protptype;
    Targrt.prototype = new F();
    Targrt.prototype.constructor = Target;
    Targrt.prototype.uber = Origin.prototype

}

Father.prototype.lastName = "wu";
function Father(){

}

function Son(){

};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章