Object.create方法的内部实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
var o = {
name: "zs",
age: 19
};
/* 01-基本使用 */
/* Object.create(o) */
/* 作用:创建一个空对象并且设置该对象的原型对象为第一个参数(o) */
var n = Object.create(o);
console.log(o);
console.log(n, "n");
var a = Object.create(Array.prototype);
console.log(a);
a.push(1, 2);
// var f = Object.create(Function.prototype);
// console.log(f);
// var d = Object.create(Date.prototype);
// console.log(d);
/* 02-创建彻底的空对象 */
/* 创建新的对象并且设置该对象的原型对象为null */
var n1 = Object.create(null);
console.log(n1);
/* 03-思考: Object.create方法的内部实现 */
Object.createNew = function(target) {
// 内部核心实现
// var o = new Object();
// o.__proto__ = target;
// return o;
}
// var n2 = Object.createNew(o);
// console.log(n2, "n2");
// var a2 = Object.createNew(Array.prototype);
// console.log(a2);
// a2.push(1, 2);
/* 04-补充(了解) */
/* Object.create(o,[options]) */
/* var n3 = Object.create(o, {
"className": {
value: "1906",
},
"id": {
value: "0001"
}
})
console.log(n3);*/
/* 默认使用上面方式创建出来的对象属性是不可以被枚举、不可以被修改、不可以被删除的 */
var n3 = Object.create(o, {
"className": {
configurable: true,
enumerable: true,
value: "1906",
writable: true
},
"id": {
value: "0001"
}
})
console.log(n3);
console.log(n3.className, n3.id);
for (var k in n3) {
console.log(k, n3[k]);
}
n3.className = "1907";
n3.id = "0002";
console.log(n3.className, n3.id);
delete n3.className;
delete n3.id;
console.log(n3);
</script>
</body>
</html>