- 对象创建方式
(1)字面量
(2) new 运算符
function NEW() {
const func = arguments[0];
const params = [].slice.call(arguments, 1);
const o = Object.create(func.prototype);
func.call(o, ...params);
return o;
}
(3)Object.create 方法
Object.create = function (obj, properties) {
function F() {}
F.prototype = obj;
let o = new F();
if (typeof properties === 'object') {
Object.defineProperties(o, properties);
}
return o;
};
- 对象拷贝
(1)浅拷贝,Object.assign 属于浅拷贝
function shadowCopy(obj) {
const newObj = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = obj[key];
}
}
}
(2)深拷贝
function deepCopy(obj, copy = {}) {
for (let key in obj) {
if (typeof obj[key] === 'object') {
copy[key] = Array.isArray(obj[key]) ? [] : {};
deepCopy(obj[key], copy[key]);
} else {
copy[key] = obj[key];
}
}
return copy;
}