如果我们假设这句话是对的:“ prototype
是用于构建__proto__
的对象”,那么Object.create的工作原理是什么?如果您这样做:
let obj1 = {
name: "obj1",
}
const obj2 = Object.create(obj1);
[当Object.create()
为obj2.__proto__
时,ob1.prototype
应如何从ob1.prototype
创建undefined
?
也许Object.create()
使用了不同于构造函数或工厂函数的另一种创建原型继承的方法?
因为,在上面的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);