我正在用javascript创建一个创建javascript对象的库。
用代码说明,如何编写下面的动物和狗函数,以便以下表达式有效:
let animal = new Animal(); // valid
let animal = Animal(); // valid also, we should return the same object
let dog = new Dog(); // valid, dog inherits/shares functions and properties from Animal.
let dog = Dog(); // valid also, same case as in previous call.
非常感谢你。
答案 0 :(得分:2)
我愿意:
function Animal(name) {
if(!(this instanceof Animal)) {
return new Animal(name);
}
this.name = name;
}
Animal.prototype.walk = function() { console.log(this.name, 'is walking...'); };
function Dog(name) {
if(!(this instanceof Dog)) {
return new Dog(name);
}
this.name = name;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
var animal = Animal('John');
var other_animal = new Animal('Bob');
var dog = Dog('Blue');
var other_dog = new Dog('Brutus');
animal.walk(); // John is walking...
other_animal.walk(); // Bob is walking...
dog.walk(); // Blue is walking...
other_dog.walk(); // Brutus is walking...
console.log(dog instanceof Animal); // true
console.log(dog instanceof Dog); // true