为什么 Obj2 无法通过 Object.Create() 从 Obj1 中找到原型函数

Why Obj2 does not find function by prototype from Obj1 via Object.Create()

我正在尝试通过 Object.create() 查看继承。我创建了 Obj1 并在其中添加了一些属性和方法。现在,当我执行 obj2 = object.create(obj1); 时,所有属性和方法也必须通过原型继承来实现。最后,为什么找到 obj2.findAge() 没有给出结果?请,有人可以帮助和纠正它吗?

<html> 
<head></head> 
<body> 
<script> 
var obj1 = {
    name: "Peter Martin",
    age: 29,
    printName: function(){
        console.log(this.name);
    },
    printAge: function(){
        console.log(this.age);
    }
}
var obj2 = Object.create(obj1);
obj2 = {
    name: "Ronald Jane",
    printName: function(){
        console.log("Hello Dear" + this.name);
    }
}
obj1.printName();
obj1.printAge();
obj2.printName();
obj2.printAge();
</script> 
</body> 
</html> 

What I want to do is use Object.Create() to get inhertiance from Obj1 to Obj2 with Obj2 having some of its own private properties. Please, help me out get this done in this example.

Object.create 之后,您将新的对象引用分配给了 obj2,但是之后您在 obj2 = { ... } 中再次更改了引用,所以您丢失了最后一个.如果你想在对象中添加额外的属性,你可以使用 Object.create 的覆盖版本或者通过 .[] 语法添加它。

findAge呢(你在post中提到了)我哪里都没有看到

var obj1 = {
    name: "Peter Martin",
    age: 29,
    printName: function(){
        console.log(this.name);
    },
    printAge: function(){
        console.log(this.age);
    }
}
var obj2 = Object.create(obj1, { 
   name: { value: 'Ronald Jane', writable: true},
   printName: { value: function() {
        console.log("Hello Dear " + this.name);
   }}
});
//obj2 = { // Here you change `obj2` to refer another object, so you have lost anything which is related to `Object.create(obj1)`
//    name: "Ronald Jane",
//   printName: function(){
//        console.log("Hello Dear" + this.name);
//    }
//}
obj1.printName();
obj1.printAge();
obj2.printName();
obj2.printAge();