老生常谈--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)。

转载于:https://www.cnblogs.com/zuiaitianxibi/p/3165605.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值