<script type="text/javascript">
/*****************
* 1.1函数继承
*****************/
//一、函数继承
function extend(Child,Parent){
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.uber = Parent.prototype;
}
//二、函数继承(拷贝) --> 只针对基本数据类型
function extend2(Child,Parent){
var p = Parent.prototype;
var c = Child.prototype;
for(var i in p){
c[i] = p[i];
}
c.uber = p;
}
/*****************
* 1.2对象继承
*****************/
//一、(浅)拷贝
function extendCopy(p){
var c = {};
for(var i in p){
c[i] = p[i];
}
c.uber = p;
return c;
}
//二、(深)拷贝
function deepCopy(p,c){
var c = c || {};
for(var i in p){
if(p.hasOwnProperty(i)){
if( typeof p[i] === "object" ){
c[i] = Array.isArray(p[i]) ? [] : {};
deepCopy(p[i],c[i]);
}else{
c[i] = p[i];
}
}
}
return c;
}
//polyfill ES3
if(typeof Array.isArray !== "function"){
Array.isArray = function(candidate){
return Object.prototype.toString.call(candidate) === '[objct Array]';
}
}
//三、object() [原型继承] --> 被es5采纳 更名为:Object.create();
function object(o){
var n;
var F = function(){};
F.prototype = o;
n = new F();
n.uber = o;
return n;
}
/*****************
* 2.原型继承、属性拷贝混合
*****************/
function objectPlus(o,stuff){
var n;
var F = function(){};
F.prototype = o;
n = new F();
n.uber = o;
for(var i in stuff){
n[i] = stuff[i];
}
return n;
}
/*****************
* 3.多重继承
*****************/
function multi(){
var n = {},stuff,j = 0, len = arguments.length;
for(j = 0; j < len; j++){
stuff = arguments[j];
for(var i in stuff){
if(stuff.hasOwnProperty(i)){
n[i] = stuff[i];
}
}
}
return n;
}
/*****************
* 4.寄生式继承
*****************/
function triangle(s,h){
//【继承】object --> 之前的原型继承函数,twoDee定义的一个对象
var that = object(twoDee);
//【】
that.name = 'triangle';
that.getArea = function(){
return this.side*this.height;
};
that.side = s;
that.height = h;
return that;
}
/*****************
* 5.构造器借用 (会出现2次继承)
*****************/
function Shape(id){
this.id = id;
}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function(){
return this.name;
}
function Triangle(){
Shape.apply(this,arguments);
}
//继承Shape的原型
Triangle.prototype = new Shape(101);
Triangle.prototype.name = 'Triangle';
var t = new Triangle(202);
//解决方案: 在 Triangle.prototype继承Shape时,不适用new;适用复制 --> extend 或者 extend2
function Shape(id){
this.id = id;
}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function(){
return this.name;
}
function Triangle(){
Shape.apply(this,arguments);
}
//继承Shape的原型
extend(Triangle,Shape);
Triangle.prototype.name = 'Triangle';