明白我们的需求是什么?
通过数组的形式去解构赋值数组时,按照数组下标的顺序进行赋值,
没有对应的值就为undefined
通过对象的形式去解构赋值对象时,按照相同的属性名进行赋值,
没有对应的值就为undefined,且可以给属性重命名。
var _const = (function() {
var obj = {};
return function(key, value) {
if (value) {
if (!obj[key]) {
Object.defineProperty(obj, key, {
get: function() {
return this["_" + key];
},
set: function(newValue) {
if (newValue == value) {
return (this.__proto__["_" + key] = newValue);
} else {
const message = `${key + "内存地址不能修改"}`;
throw new Error(message);
}
},
});
obj[key] = value;
} else {
throw new Error("不能重复声明" + key);
}
return obj;
} else {
throw new Error("声明常量必须赋值");
}
};
})();
var _let = (function() {
var obj = {};
return function(key, value) {
if (!obj[key]) {
Object.defineProperty(obj, key, {
get: function() {
return this["_" + key];
},
set: function(newValue) {
return (this.__proto__["_" + key] = newValue);
},
});
obj[key] = value;
} else {
throw new Error("不能重复声明" + key);
}
return obj;
};
})();
var _var = function(key, value) {
this.key = value;
};
var selectModifier = function(modifier) {
if (modifier === "const") {
return _const;
} else if (modifier === "let") {
return _let;
} else {
return _var;
}
};
const _deconstruction = (function() {
function isArray(modifier, value, originalValue) {
var result = {};
for (const index in value) {
if (originalValue[index]) {
result = selectModifier(modifier)(value[index], originalValue[index]);
} else {
result = selectModifier(modifier)(value[index], "undefined");
}
}
return result;
}
function isObject(modifier, value, originalValue) {
var result = {};
for (const name in value) {
if (originalValue.hasOwnProperty(name)) {
result = selectModifier(modifier)(value[name], originalValue[name]);
} else {
result = selectModifier(modifier)(value[name], "undefined");
}
}
return result;
}
return function(modifier, value, originalValue) {
return value instanceof Array ?
isArray(modifier, value, originalValue) :
value instanceof Object ?
isObject(modifier, value, originalValue) :
null;
};
})();
function fn() {
var obj = _deconstruction(
"const", { name: "newName", d: "d" }, { name: "zhangsan", age: 20 }
);
console.log(obj.newName);
console.log(obj.d);
var arr = _deconstruction("const", ["a", "b", "c"], [1, 2]);
console.log(arr.a);
console.log(arr.b);
console.log(arr.c);
}
fn();