我們一般常用的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è)類型的拷貝方法,如下
- null、number、string、undefined、bool類型的數(shù)據(jù)。拷貝時(shí)候直接返回對應(yīng)的值
- Date、RegExp。通過valueOf生成new一個(gè)新的對象。注意RegExp的時(shí)候,需要設(shè)置是否忽略大小寫等配置
- 函數(shù)。調(diào)用新函數(shù)的時(shí)候,執(zhí)行對拷貝函數(shù)的調(diào)用,更改this的指向。同時(shí),注意函數(shù)也是一個(gè)對象,可以設(shè)置屬性等,所以不要忘記對函數(shù)屬性的拷貝
- 對象
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ò)誤的地方,歡迎大家指正