原文連接:http://js8.in/698.html.html
第一種方法是使用prototype屬性:jquery
這裏也能夠直接Child.prototype=new P();考慮到P構造函數的參數沒法肯定,因此使用一個空函數。數組
function extend(Child,Parent){ var F=function(){}; F.prototype=Parent.prototype; Child.prototype=new F(); Child.prototype.constructor=Child; }
第二種方法則是屬性和方法的拷貝:jquery插件
function extend(Child,Parent){ var c=Child.prototype; var p=Parent.prototype; for(var i in p){ c[i]=p[i]; } };
其實對象繼承包括淺拷貝和深度拷貝。函數
淺度拷貝:淺拷貝的對象,其實引用的是同一地址。好比 var a={name:'xiaoqiang'},b={};b=a;b.name='lalala';當我修改了b的時候,a也就發生了改變。spa
深度拷貝:深度拷貝後的對象,修改任一對象,另外一對象都不受影響。prototype
淺拷貝示例:插件
function lightlyCopy(obj){ var c={}; for(var i in obj){ c[i]=obj[i]; } return c; }
使用prototype進行拷貝:code
function lightlyCopy(obj){ var F=function(){}; F.prototype=obj; return new F(); }
深度拷貝:這個。。。htm
// extends 'from' object with members from 'to'. If 'to' is null, a deep clone of 'from' is returned function extend(from, to) { if (from == null || typeof from != "object") return from; if (from.constructor != Object && from.constructor != Array) return from; if (from.constructor == Date || from.constructor == RegExp || from.constructor == Function || from.constructor == String || from.constructor == Number || from.constructor == Boolean) return new from.constructor(from); to = to || new from.constructor(); for (var name in from) { to[name] = typeof to[name] == "undefined" ? extend(from[name], null) : to[name]; } return to; }
以上參考自:http://stackoverflow.com/questions/122102/most-efficient-way-to-clone-an-object。
實際上,若遞歸的對象是個數組的話,也只能用for in,由於for是沒法枚舉到數組的屬性成員的。好比:
var a=[1,3,2]; a.test='hahahah'; for(var i=0,len=a.length;i<len;i++){ console.log(a[i]);//讓a.test情何以堪吶 }
jquery中也有extend方法,咱們一般在寫jquery插件時候就會用到。可是,它的第一個參數默認爲false,若設置爲true,則是深拷貝。