老生常谈--Js继承小结

      一直以来,对Js的继承有所认识,但是认识不全面,没什么深刻印象。于是,经常性的浪费很多时间重新看博文学习继承,今天工作不是特别忙,有幸看到了http://www.slideshare.net/stoyan/javascript-patterns?from_search=9 (该博文作者同样是《Javascript Patterns》一书的作者,效力于Yahoo,是YSlow 的架构者和smush.it的作者),在此,自己做一些小结和笔录以免多次重复学习。

js继承:

/*******继承1:复制父亲对象所有属性-->子对象**********/
function extend(parent, child){
var child = child || {};
for(var prop in parent){
child[prop] = parent[prop];
}
return child;
}

/*******混合继承:从多个对象中继承****************/
function mixInThese(){
var args = arguments,
child = {};
for(var i = 0, len = args.length; i < len; i++){
for(var prop in args[i]){
child[prop] = args[i][prop];
}
}
return child;
}
var cake = mixInThese(

       {"oil": 3, "button": 4},

       {"weight": 34},

      {"tasty": "sweet"});
console.log(cake);

/*************经典继承 原型继承 ES标准推荐 继承方式1***************************/
function inherit(parent, child){
child.prototype = new Parent();
}

/**********借用构造函数    继承方式2********/
function Child(){
Parent.apply(this, arguments);
//anything else
}

优点:创建对象的时候,可以传递参数到父亲对象

缺点:没有继承Prototype原型链上的属性

/*****************/

/***********借用构造函数 + 原型继承 继承方式3*****************/
function Child(){
Parent.apply(this, arguments);
}
Child.prototype = new Parent();

 

/**************父子对象共用同一份prototype*  继承方式4*********************************/
function inherit(parent, child){
child.prototype = child.prototype;
};

优点:父子对象共用同一份prototype

缺点:父子对象共用同一份prototype

/***********只继承prototype上的属性(父子对象不共用同一份prototype) 继承方式5************/
function inherit(parent, child){
function F(){}
F.prototype = parent.prototype;
child.prototype = new F();

child.uber = parent.prototype;

child.prototype.constructor = child;
}

/**********原生式继承Prototypal inhert************/

function object(o){

    function F(){}

   F.prototype = o;

   return new F();

}

 

原生式继承总结(道格拉斯总结):

1.没有像类(Class-Like)一样的构造函数(Constructor)(英文原文:no class-like constructors).

2.对象和对象之间直接通过原型实现继承(而不像其他语言中的类和类之间的继承)(英文原文:objects inherits from objects)。

posted on 2013-07-01 20:29  zuiaitianxibi  阅读(1142)  评论(1编辑  收藏  举报

导航