在第二个代码中"Bird.prototype和Dog.prototype不是Animal"的实例;
为什么会这样?第一个代码中没有这样的问题。
//First
function Animal() { }
function Bird() { }
function Dog() { }
Bird.prototype = Object.create(Animal.prototype);
Dog.prototype = Object.create(Animal.prototype);
// Only changes in code below this line
Bird.prototype.constructor=Bird;
Dog.prototype.constructor=Dog;
let duck = new Bird();
let beagle = new Dog();
//Second
function Animal() { }
function Bird() { }
function Dog() { }
Bird.prototype = Object.create(Animal.prototype);
Dog.prototype = Object.create(Animal.prototype);
// Only change code below this line
Bird.prototype={constructor:Bird};
Dog.prototype={constructor:Dog};
let duck = new Bird();
let beagle = new Dog();
在第一个示例中,您修改分配给prototype
的对象。
在第二个示例中,您替换它。
const thing = { a: "value" };
const a = {};
const b = {};
a.example = Object.create(thing);
b.example = Object.create(thing);
a.example.b = "other";
b.example = { different: "object" };
console.log( { a, b } );