【问题标题】:Javascript create objects with both new and without new + inheritanceJavascript 创建具有 new 和不具有 new + 继承的对象
【发布时间】:2017-04-21 14:43:03
【问题描述】:

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

  1. 如何编写库的界面,以便他们的用户可以 创建有和没有新的对象? (我看到很多答案都建议构造函数使用 new 自动调用自身,如果它们不是首先用 new 调用的,但不是相反)。
  2. 我们可以在 Object.create 中使用 new 吗?例如: let dog = new Object.create(animal);
  3. 如何提供继承

用代码来说明,下面的函数Animal和Dog怎么写才能使下面的表达式有效:

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.

非常感谢。

【问题讨论】:

  • 如果构造函数返回一个对象,new 将不起作用。也许调查一下。 Example.
  • this book 的第 3 章可能会有所帮助。
  • 那么我可以直接返回 Object.Create 吗?无论有没有新的,它都可以工作(包括继承)?

标签: javascript inheritance constructor factory


【解决方案1】:

我愿意:

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

【讨论】:

  • 你必须在Dog.prototype = Animal.prototype之后将Dog的构造函数设置为Dog。并且不要忘记输入一些分号。
  • 我认为您将 Animal.prototype.constructor 设置为 Dog 因为您没有克隆原型。
  • 我想知道是否有办法在Animal.prototype 上设置name,以便Dog 继承它。
  • @StevenLiekens 我认为 Dog 构造函数中的 Animal.call(this, name);(替换 this.name = name;)会做到这一点
  • 这仍然最终分配给this.name,这与Dog.prototype.name不同。也许这是正确的行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-13
  • 1970-01-01
  • 1970-01-01
  • 2018-05-09
  • 2020-09-18
相关资源
最近更新 更多