天天看点

js继承的几种方法

//继承的几种方法
//1.传统形式    继承过多没用的东西
// Father.prototype.name = 'hzl';
// function Father(){
//     this.sex = 'male';
// }
// var father = new Father();
// Son.prototype = father;
// function Son() {  
// }
// var son = new Son();
// console.log(son.sex);     //male
// console.log(son.name);     // hzl


// 2.借用构造函数   不能集成构造函数原型    每次构造都要多走一个函数
// function Father(name,sex,age){
//     this.name = name;
//     this.sex = sex;
//     this.age = age;
// }
// function Son(name, sex, age, marry) { 
//     Father.call(this,name,sex,age);          Father.apply(this,[name,sex,age])
//     this.marry = marry;
//  }
//  var son = new Son('1','2','3','4');


//3.共享模式
//                     Father prototype 
//  Father                                       Son
//  缺点 一旦改Son的原型Father原型也改动  
//  此时Father和Son的引用指向同一个房间    堆数据

// Father.prototype.name = 'hzl';
// function Father(){
// }
// Son.prototype = Father.prototype;
// function Son(){
// }
// var son = new Son();


//4. 圣杯模式
// Father.prototype.name = 'hzl'
// function Father(){

// }
// function Son(){

// }
// function inherit(Target,origin){
//     function nul(){};
//     nul.prototype = origin.prototype;
//     Target.prototype = nul.prototype;
//     Target.prototype.constructor = Target;   没有这一句constructor返回Father(){}
//     Target.prototype.uber = origin.prototype;     记录最终继承自谁的原型
// }
// inherit(Son,Father);
// var son = new Son;


//改善   YUI3 建议
// Father.prototype.name = 'hzl'
// function Father(){

// }
// function Son(){

// }
// var inherit = (function(){
//     function nul(){};
//     return function(Target,Origin){
//         nul.prototype = Origin.prototype;
//         Target.prototype = nul.prototype;
//         Target.prototype.constructor = Target; 
//         Target.prototype.uber = Origin.prototype;
//     }
// }())
    
// inherit(Son,Father);
// var son = new Son;
           

继续阅读