對象的復(fù)制

我們一般常用的js類型有5種基本類型(undefined、null、number、string、boolean)和Object。其中Object又包含Date、RegExp、Array、Function這些常用的類型。以下是一個(gè)函數(shù),可以更細(xì)致的區(qū)分?jǐn)?shù)據(jù)的類型。函數(shù)主要是參考了@wengjq的文章javaScript中淺拷貝和深拷貝的實(shí)現(xiàn) #3。個(gè)人在此基礎(chǔ)上,做了一點(diǎn)微調(diào)

(function ($) {
    var types = 'Array Object String Date RegExp Function Boolean Number Null Undefined'.split(' ');
    types.forEach(type => ($['is' + type] = obj => Object.prototype.toString.call(obj).slice(8, -1) === type))
})(window.$ || (window.$ = {}))

對代碼進(jìn)行測試

var a = [[], {}, 'hello', new Date(), /^a/, () => {}, true, 11, null, undefined]
var b = a.map((item, i) => {
    let type = Object.prototype.toString.call(item).slice(8, -1)
    return {
        item,
        type: type.toLowerCase(),
        typeof: typeof item,
        ['is' + type]: $['is' + type](item)
    }
})
console.log(b)

可以看到輸出結(jié)果


image.png

有了這個(gè)函數(shù),可以很方便在對象的拷貝,進(jìn)行一些類型的判斷。對于各個(gè)類型的拷貝方法,如下

  1. null、number、string、undefined、bool類型的數(shù)據(jù)。拷貝時(shí)候直接返回對應(yīng)的值
  2. Date、RegExp。通過valueOf生成new一個(gè)新的對象。注意RegExp的時(shí)候,需要設(shè)置是否忽略大小寫等配置
  3. 函數(shù)。調(diào)用新函數(shù)的時(shí)候,執(zhí)行對拷貝函數(shù)的調(diào)用,更改this的指向。同時(shí),注意函數(shù)也是一個(gè)對象,可以設(shè)置屬性等,所以不要忘記對函數(shù)屬性的拷貝
  4. 對象
    1 拷貝對象的__proto__
    2 拷貝對象的constructor
    3 拷貝對象的屬性。個(gè)人建議使用Object.getOwnPropertyNames而不使用for...in來獲取屬性。第一:for...in會獲取繼承來的屬性,繼承而來的屬性,應(yīng)該繼承不應(yīng)該賦值給拷貝對象。第二:for...in無法獲取不可枚舉屬性

代碼如下

function copy(obj, deep) {
    if(obj === null || (typeof obj !== 'object' && !$.isFunction(obj))) return obj
    if ($.isDate(obj)) return new Date(obj.valueOf())
    if ($.isRegExp(obj)) {
        let config = obj.ignoreCase ? 'i' : ''
            + obj.global ? 'g' : ''
            + obj.multiline ? 'm' : ''
        return new RegExp(obj.valueOf(), config)
    }
    if ($.isFunction(obj)) {
        let fn = function () { obj.apply(this, arguments) }
        copyProperty(obj, fn, deep)
        return fn
    }
    if ($.isArray(obj)) return obj.map(v => copy(v, deep))
    return copyObj(obj, deep)
}

function copyObj (obj, deep) {
    let target = Object.create(Object.getPrototypeOf(obj))
    Object.defineProperty(target, 'constructor',  {
        value: obj.constructor,
        configurable: true,
        enumerable: false,
        writable: true
    })
    copyProperty(obj, target, deep)
    return target
}
function copyProperty (obj, target, deep) {
    Object.getOwnPropertyNames(obj).forEach(key => {
        let desps = Object.getOwnPropertyDescriptor(obj, key)
        Object.defineProperty(target, key, {
            value: deep ? copy(obj[key]) : desps.value,
            configurable: desps.configurable,
            enumerable: desps.enumerable,
            writable: desps.writable
        })
    })
}

簡單寫了一點(diǎn)測試代碼

var a = {aa: 11}
var b = Object.create(a)
Object.defineProperty(b, 'cc', {value: '100', enumerable: false})

var fun = function() { console.log(arguments, this) }
fun.aa = Object.create(b)

var arr = ['', true, undefined, null, 19, new Date(), /9{2}/ig, [a, b, fun], fun, {a, b, fun}]
var arrCopy = copy(arr, true)
arrCopy.forEach((v, i) => console.log(v === arr[i], v))

運(yùn)行結(jié)果如圖


image.png

有錯(cuò)誤的地方,歡迎大家指正

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容