一、typeof 和 instanceof的区别:
- typeof判断所有变量的类型,返回值有number、string、boolean、function、object、undefined。
- instanceof用来判断对象,代码形式(obj1 instanceof obj2)(判断obj1是否为obj2的实例),obj2必须为对象,否则会报错。返回的是布尔值
二、Object.prototype.hasOwnProperty.call():
用来判断一个属性是定义在对象本身而不是继承自原型链。
三、原型:
- 所有引用类型都有一个__proto__(隐式原型)属性,属性值是一个普通的对象
- 所有函数都有一个prototype(原型)属性,属性值是一个普通的对象
- 所有引用类型的__proto__属性指向它构造函数的prototype
四、原型链:
当访问一个对象的某个属性时,会先在这个对象本身属性上查找,如果没有找到,则会去它的__proto__隐式原型上查找,即它的构造函数的prototype,如果还没有找到就会再在构造函数的prototype的__proto__中查找,这样一层一层向上查找就会形成一个链式结构,我们称为原型链。
五、TS代码:
/**
* 判断对象是否为数组
* @param obj
* @returns
*/
private static IsArray(obj: any) {
return obj && typeof obj == "object" && obj instanceof Array;
}
/**
* 对象深拷贝
* @param tSource
* @returns
*/
public static DeepClone<T>(tSource: T, tTarget?: Record<string, any> | T): T {
if (this.IsArray(tSource)) {
tTarget = tTarget || [];
} else {
tTarget = tTarget || {};
}
for (const key in tSource) {
if (Object.prototype.hasOwnProperty.call(tSource, key)) {
if (typeof tSource[key] === "object" && typeof tSource[key] !== null) {
tTarget[key] = this.IsArray(tSource[key]) ? [] : {};
this.DeepClone(tSource[key], tTarget[key]);
} else {
tTarget[key] = tSource[key];
}
}
}
return tTarget as T;
}
/**
* 对象浅拷贝
* @param tSource
* @returns
*/
public static SimpleClone<T>(tSource: T, tTarget?: Record<string, any> | T): T {
if (this.IsArray(tSource)) {
tTarget = tTarget || [];
} else {
tTarget = tTarget || {};
}
for (const key in tSource) {
if (Object.prototype.hasOwnProperty.call(tSource, key)) {
tTarget[key] = tSource[key];
}
}
return tTarget as T;
}