在第二个代码中“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 } );
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句