js 實現深拷貝 保留繼承關係 可以實現各種類型的拷貝及實現遞歸拷貝

function deepClone(obj) {
    if (typeof obj !== 'object') return Object;
    if (obj === null) return null;
    if (obj instanceof Date) return new Date(obj);
    if (obj instanceof RegExp) return new RegExp(obj);
    // Object.prototype.toString.call(obj) === '[object Array]'

    let o = new obj.constructor();

    for (const key in obj) {
    	if (obj.hasOwnProperty(key)) {
    		o[key] = typeof obj[key] === 'object' ? deepClone(obj[key]): obj[key];	
    	}
    }
    return o;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章