gpt4 book ai didi

javascript - new 与 Object.create() 之间的真正区别是什么

转载 作者:行者123 更新时间:2023-11-29 10:04:01 25 4
gpt4 key购买 nike

<分区>

我试图了解关键字 newObject.create() 之间的真正区别

解释:

  • a1函数a2对象
  • a1a2key1 作为默认属性。 key2 在从它们创建实例 bxx 之后被分配。检查 bxx 是独立对象本身还是只是一个引用。

"use strict";

function a1() {
this.key1 = "value 1";
}

let a2 = {
key1: "value 1"
};

let b1new, b1obj, b2new, b2obj;

try {
b1obj = Object.create(a1);
} catch (e) {
console.error("Error a1: ", e.message)
}
try {
b1new = new a1();
} catch (e) {
console.error("Error a1: ", e.message)
}


try {
b2obj = Object.create(a2);
} catch (e) {
console.error("Error a2: ", e.message)
}
try {
b2new = new a2();
} catch (e) {
console.error("Error a2: ", e.message)
}

//let b = new a();

a1.key2 = "value 2";
a2.key2 = "value 2";

if (b1obj) {
console.log("b1obj.key1: ", b1obj.key1);
console.log("b1obj.key2: ", b1obj.key2);
}
if (b1new) {
console.log("b1new.key1: ", b1new.key1);
console.log("b1new.key2: ", b1new.key2);
}
if (b2obj) {
console.log("b2obj.key1: ", b2obj.key1);
console.log("b2obj.key2: ", b2obj.key2);
}
if (b2new) {
console.log("b2new.key1: ", b2new.key1);
console.log("b2new.key2: ", b2new.key2);
}

输出:

"Error a2: " "a2 is not a constructor"    
"b1obj.key1: " undefined
"b1obj.key2: " "value 2"
"b1new.key1: " "value 1"
"b1new.key2: " undefined
"b2obj.key1: " "value 1"
"b2obj.key2: " "value 2"

问题:

  1. 为什么不能在 a2 上使用 new
  2. 为什么 b1obj.key1undefined
  3. 为什么 b2obj.key2 仍然引用父级的属性?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com