一直以来,对Js的继承有所认识,可是认识不全面,没什么深入印象。因而,常常性的浪费不少时间从新看博文学习继承,今天工做不是特别忙,有幸看到了http://www.slideshare.net/stoyan/javascript-patterns?from_search=9 (该博文做者一样是《Javascript Patterns》一书的做者,效力于Yahoo,是YSlow 的架构者和smush.it的做者),在此,本身作一些小结和笔录以避免屡次重复学习。javascript
js继承:java
/*******继承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(app
{"oil": 3, "button": 4},ide
{"weight": 34},函数
{"tasty": "sweet"});
console.log(cake);学习
/*************经典继承 原型继承 ES标准推荐 继承方式1***************************/
function inherit(parent, child){
child.prototype = new Parent();
}this
/**********借用构造函数 继承方式2********/
function Child(){
Parent.apply(this, arguments);
//anything else
}.net
优势:建立对象的时候,能够传递参数到父亲对象prototype
缺点:没有继承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)。