如果我们假设这句话是正确的:“prototype
是用于构建__proto__
的对象”,那么Object.create如何工作?如果您这样做:
let obj1 = {
name: "obj1",
}
const obj2 = Object.create(obj1);
当 ob1.prototype
时,Object.create()
应如何从 ob1.prototype
创建 obj2.__proto__
是未定义
??
也许 Object.create()
使用另一种创建原型(prototype)继承的方法,而不是构造函数或工厂函数?
因为,在上面的 Object.create()
示例中,这是正确的:
console.log(obj2.__proto__ === obj1);
但是如果我们对构造函数做同样的事情,这将是正确的:
console.log(obj2.__proto__ === obj1.prototype);
使用函数构造对象:
function obj1(name) {
this.name = name;
}
const obj2 = new obj1();
我错过了什么吗?
最佳答案
你的句子“prototype
是用于构建__proto__
的对象”仅适用于function
被调用 new
。例如
let dog = new Animal();
等于:
let dog = Object.create(Animal.prototype); // <<<
Animal.call(dog);
原型(prototype)继承本身仅意味着对象包含对其原型(prototype)的“内部”( __proto__
)引用。与Object.create
您创建一个对象,其原型(prototype)设置为传递的对象。因此
let inherited = Object.create(obj)
相当等于
let inherited = {};
inherited.__proto__ = obj;
关于javascript - 当 ob1.prototype 未定义时,Object.create() 如何从 ob1.prototype 创建 obj2.__proto__ ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59492494/