// 这个方法我们可以封装成一个函数来实现继承 function extend(child,father) { functionF(){} F.prototype = father.prototype; child.prototype = new F(); child.prototype.constructor = child; }
非构造函数实现的继承
1.利用Object.create函数
1 2 3 4 5 6 7 8 9
var a = { m:0, n:8 } // 为a创建一个prototype属性使其指向a ,模仿构造器 // 因为对像没有prototype属性 a.prototype = a; // 利用Object.create函数创建一个对象b使其继承a var b = Object.create(a);
2.利用空对象构造object方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
var a = { m:0, n:8 } // 传入一个对象(因为构造函数的原型也是一个对象) // 把空函数的prototype指向该对象 // 返回一个对象实例 // 调用该方法后b即为返回的对象实例 // 同样模仿构造器把a.prototype指向a function object(o){ functionF(){} F.prototype = o; o.prototype = o; return new F(); } var b = object(a);
3.浅拷贝继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
var a = { m:0, n:8, x:[1,2,3], y:{ a:7 } } function extend(a){ var result = {}; for(var i in a) { result[i] = a[i]; } return result; } var b = extend(a);
function extend(a,result){ var result = result || {}; for(var i in a) { if(typeof a[i] === 'object') { result[i] = (a[i].constructor === Array) ? [] : {}; extend(a[i],result[i]); } else { result[i] = a[i]; } } return result; } var b = extend(a);