JavaScript基础教程

JS(十五)继承模式,命名空间,对象枚举(上)

2018-03-17  本文已影响15人  StevenTang

写在最前面

继承的发展史

原型链的继承


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(){
    
};

上一篇下一篇

猜你喜欢

热点阅读