Javascript使用new和without +继承创建对象

时间:2017-04-21 14:43:03

标签: javascript inheritance constructor factory

我正在用javascript创建一个创建javascript对象的库。

  1. 如何编写库的界面以便用户可以 创建WITH和WITHOUT这样的对象? (我看到很多答案提出构造函数,如果没有首先使用new调用自动调用自身,而不是相反的方法)。
  2. 我们可以在Object.create中使用new吗?例如: let dog = new Object.create(animal);
  3. 如何提供继承
  4. 用代码说明,如何编写下面的动物和狗函数,以便以下表达式有效:

    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.
    

    非常感谢你。

1 个答案:

答案 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