首页 > 代码库 > JavaScript中的继承

JavaScript中的继承

一、原型链(默认)

function Person(){};

function Student(){};

Student.prototype = new Person();

Student.prototype.constructor = Student;

缺点:1、传参怎么搞 ? 2、new Person的实例属性成了Student的原型属性

二、借用构造函数

function Person(name) { this.name = name;}

function Student(name, klass) { Person.call(this, name);  this.klass = klass;}

优点:传参搞定了哦  缺点:方法继承呢 继承 呢

三、组合继承(原型链+借用构造函数)

 1 function Person(name){
 2     this.name = name;
 3 }
 4 
 5 function Student(name, klass){
 6     Person.call(this, name);
 7     this.klass = klass;
 8 }
 9 
10 Student.prototype = new Person();
11 Student.prototype.constructor = Student;

还存在缺点:1、new Person的实例属性成了Student的原型属性  2 Person构造函数被调用了两次,效率低下

四、临时构造函数

 1 function Person(name){
 2     this.name = name;
 3 }
 4 
 5 function Student(name, klass){
 6     Person.call(this, name);
 7     this.klass = klass;
 8 }
 9 
10 (function(){
11     var F = function(){};
12     F.prototype = Person.prototype;
13     Student.prototype = new F();
14     Student.prototype.constructor = Student;
15 })();

看起来不错哦~~

但素,JavaScript为啥非得类式继承捏

重点来了,

 

原型继承

Student.prototype = Object.create(Person.prototype);

Student.prototype.constructor = Student;

 

原型链,链起来:new student() -----> Student.prototype----->Person.prototype-----> Object.Prototype 

把你的心,我的心,串一串,串一株幸运草,串一个同心圆~~

Object.create polyfill

if(typeof Object.create !== ‘function‘){
    Object.create = function(o){
        var F = function(){};
        F.prototype = o;
        return new F();
    }
}

 

 

额外的,通过复制属性实现继承

 1 function extendDeep(parent, child){
 2     var i;
 3     child = child || {};
 4     for(i in parent){
 5         if(parent.hasOwnProperty(i)){
 6             if(typeof parent[i] === ‘object‘){
 7                 child[i] = (Object.prototype.toString.call(parent[i]) === ‘[object Array]‘) ? [] : {};
 8                 extendDeep(parent[i], child[i]);
 9             }else{
10                 child[i] = parent[i];
11             }
12         }
13     }
14     return child;
15 }

 

JavaScript中的继承